Benjamin
Benjamin

Reputation: 655

React Native AsyncStorage: using await and async

I'm trying to get all keys from my AsyncStorage database and then filter them in another function, can't seem to get it to wait until AsyncStorage has returned the data?

This function returns the keys in an array:

DATABASE_getAllCoffeeEntries =  () => {
    AsyncStorage.getAllKeys((err, keys) => {})
    .then(keys => {
      AsyncStorage.multiGet(keys, (error, items) => { 
       return items;
      }).then(items => {
        return items; // array of items is returned
      });
  });
 }

and this function is meant to call the function above then wait for the result then filter down the data.

somefunc = async () => {
  var items = await DATABASE_getAllCoffeeEntries();
  var someItems = items.filter(function (result, i, item) {
          // do filtering stuff
          return item;
    });

    // do something with filtered items 
}

Have tried a lot on here but can't get my head around it... any help would be great, thanks.

Upvotes: 1

Views: 4402

Answers (1)

Andrew
Andrew

Reputation: 28539

You need to actually return something from your DATABASE_getAllCoffeeEntries

You could do something like this.

  1. First we wrap your call inside a promise. Which will resolve if we get all the items from AsyncStorage or reject if there is a problem.
  2. Make sure that our calls to AsyncStorage are inside a try/catch. await calls can throw so we need to make sure that we handle any errors.
  3. Use async/await when getting the items from AsyncStorage as this gets ride of the callbacks that are trapping the responses from AsyncStorage. It also can make your code easier to read

Here is the refactor

DATABASE_getAllCoffeeEntries = () => {
  return new Promise( async (resolve, reject) => {
    try {
      let keys = await AsyncStorage.getAllKeys();
      let items = await AsyncStorage.multiGet(keys)
      resolve(items)
    } catch (error) {
      reject(new Error('Error getting items from AsyncStorage: ' + error.message))
    }
  });
}

Then we can call the function like this, though we will have to wrap it in a try/catch as it can throw.

somefunc = async () => {
  try {
    var items = await this.DATABASE_getAllCoffeeEntries();
    var someItems = items.filter(function (result, i, item) {
          // do filtering stuff
          return item;
    });
    // do something with filtered items 
  } catch (error) {
    // do something with your error
  }
}

Upvotes: 3

Related Questions