簡體   English   中英

如何在 javascript 中返回 map 內的承諾數組

[英]How to return array of promises inside map in javascript

function handler(){
    const results = [].map((item) => {
      a();
      b();
    })
    Promise.allSettled(results);
  }

  function a() {
    // returns promise
  }
  function b() {
    // returns promise
  }
}

如何修改上面的代碼,以便我可以將承諾數組傳遞給promise.allSettled(results)

我試過了但不確定這是否正確?

function handler() {
    const results = [].map((item) => {
      const out1 = a();
      const out2 = b();
      return [...out1, ...out2];
    })
    Promise.allSettled(results);
}

使用平面地圖

 const a = [1,2,3,4,5,6]; const b = a.flatMap(v => [Promise.resolve(a), Promise.reject(a)]) Promise.allSettled(b).then(x => console.log(x));

這應該工作

function handler() {
    const results = [].map((item) => {
      const out1 = a();
      const out2 = b();
      return [...out1, ...out2];
    })
    Promise.allSettled(results.flat());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM