简体   繁体   中英

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?

Make an array of Promises and call Promise.all on it before filtering:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM