简体   繁体   English

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

[英]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.

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