Search code examples
javascriptnode.jsreact-nativeasync-awaitarray-filter

React native - How to filter array asynchronous (async/await)


I have a filter method:

_filterItems(items) {
  return items.filter(async item => {
    let isTrue = await AsyncStorage.getItem('key');
    return isTrue;
  })
}

Call the method this._filterItems(myItemsAsArray) always return undefined.

How can I make it works as expected?


Solution

  • I assume by AsyncStorage.getItem('key'); you meant AsyncStorage.getItem(item);

    async function run(){
        let result =  await Promise.all(items.map((item)=>AsyncStorage.getItem(item)));
      result = result.filter(Boolean); // filter all non-truthy values
      console.log('result',result);
    
    }
    
    run();
    

    here it is https://jsfiddle.net/2juypmwL/1/

    Technically, you can make it even shorter :

    async function run(){
        let result =  (await Promise.all(items.map(AsyncStorage.getItem))).filter(Boolean);
      console.log('result',result);
    }
    
    run();