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
2 Answers
Reset to default 4I 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))