簡體   English   中英

javascript/Typescript 在 .then 內返回 array.filter 內的回調

[英]javascript/Typescript return inside .then callback inside array.filter

我想過濾一個數組,但要做到這一點,我需要調用返回承諾的數據庫。 代碼:

this.arrayToFilter.filter(myObject => {
    this.dataBaseService.getSomething(myObject.id).then(something => {
        // some calculations
        return shouldBeFiltered 
    })
})

如何將shouldBeFiltered的值shouldBeFiltered到過濾器回調中?

創建一個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