[英]javascript/Typescript return inside .then callback inside array.filter
I want to filter an array but to do that I need to call my database that returns a promise.我想过滤一个数组,但要做到这一点,我需要调用返回承诺的数据库。 Code:
代码:
this.arrayToFilter.filter(myObject => {
this.dataBaseService.getSomething(myObject.id).then(something => {
// some calculations
return shouldBeFiltered
})
})
How can I get the value of shouldBeFiltered
to the filter callback?如何将
shouldBeFiltered
的值shouldBeFiltered
到过滤器回调中?
Make an array of Promises and call Promise.all
on it before filtering:创建一个
Promise.all
数组并在过滤之前调用Promise.all
:
const shouldBeFilteredArr = await Promise.all(
this.arrayToFilter.map(({ id }) => this.dataBaseService.getSomething(id)
);
const filteredItems = this.arrayToFilter.filter((myObject, i) => {
const something = shouldBeFilteredArr[i];
// some calculations
return shouldBeFiltered;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.