最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React native - How to filter array asynchronous (asyncawait) - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jul 2, 2018 at 16:56 Gold ChickenGold Chicken 3958 silver badges16 bronze badges 2
  • This is probably a duplicate of Filtering an array with a function that returns a promise – Garrett Motzner Commented Jul 2, 2018 at 17:04
  • Could someone give me a simple solution? I have already tried many ways on google but cannot resovle the issue :( – Gold Chicken Commented Jul 2, 2018 at 17:25
Add a ment  | 

2 Answers 2

Reset to default 4

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/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();

You cannot use an async function with the array .filter method directly, since that method expects a boolean to be returned but an async function will always return a promise. Instead, you can provide a simple wrapper for it that will allow the promises to resolve first, then uses the result of those promises as the filter condition.

Example:

const items = Array(10).fill().map((_, i) => i);

function asyncFilter(arr, func) {
  return Promise.all(arr.map(func)).then(boolArr => arr.filter((_, i) => boolArr[i]));
}

asyncFilter(items, async n => Boolean(n % 2)).then(result => console.log(result))

发布评论

评论列表(0)

  1. 暂无评论