4

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?

2

2 Answers 2

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.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();
Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.