Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
Gold Chicken Avatar asked Oct 24 '25 09:10

Gold Chicken


1 Answers

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();
like image 125
Milad Avatar answered Oct 25 '25 23:10

Milad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!