Resolve *and* reject all promises in Bluebird

本小妞迷上赌 提交于 2019-12-06 10:25:26

Added answer for completeness since OP asked. Here is what I'd do:

 const res = Promise.all(promises.map(p => p.reflect())) // get promises
   .then(values => [
          values.filter(x => x.isFulfilled()).map(x => x.value()), // resolved
          values.filter(x => x.isRejected()).map(x => x.reason()) // rejected
   ]);

There's nothing built in for it, but reduce can make it pretty succinct:

Promise
  .settle(promises)
  .reduce(([resolved, rejected], inspection) => {
    if (inspection.isFulfilled())
      resolved.push(inspection.value());
    else
      rejected.push(inspection.reason());
    return [resolved, rejected];
  }, [[], []]);

You can use Promise.all(), handle rejected Promise, return reason or other value to chained .then()

let promises = [
  Promise.resolve("resolved"),
  Promise.resolve("resolved"),
  Promise.reject("rejected")
]
, results = {resolved:[], rejected:[]}

, resolvedAndRejected = Promise.all(
  promises.map((p) => {
    return p.then((resolvedValue) => {
      results.resolved.push(resolvedValue);
      return resolvedValue
    }, (rejectedReason) => {
      results.rejected.push(rejectedReason);
      return rejectedReason
    })
  }));

resolvedAndRejected.then((data) => {
  console.log(data, results)
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!