javascript / Typescript返回.then在array.filter内部回调

我想过滤一个数组,但是要做到这一点,我需要调用返回promise的数据库。 码:

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?

评论
  • mneque
    mneque 回复

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