简体   繁体   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
  }
}

How to modify the above code so that I can pass array of promises to promise.allSettled(results)如何修改上面的代码,以便我可以将承诺数组传递给promise.allSettled(results)

I tried this but not sure if this is correct way?我试过了但不确定这是否正确?

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

Use flatMap使用平面地图

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

This should work这应该工作

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