admin管理员组文章数量:1382169
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))
本文标签: javascriptReact nativeHow to filter array asynchronous (asyncawait)Stack Overflow
版权声明:本文标题:javascript - React native - How to filter array asynchronous (asyncawait) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744426037a2605694.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论