Allow * and * reject all promises in Bluebird

I am looking for a way to get both permissions and deviations from an array of promises. I am currently counting on a Bluebird implementation, so the solution is compatible with ES6.

The best thing that comes to mind is to use Bluebird Promise.settlefor this, and I believe inspections promise unnecessary complication here:

  let promises = [
    Promise.resolve('resolved'),
    Promise.resolve('resolved'),
    Promise.reject('rejected')
  ];

  // is there an existing way to do this?
  let resolvedAndRejected = Promise.settle(promises)
  .then((inspections) => {
    let resolved = [];
    let rejected = [];

    inspections.forEach((inspection) => {
      if (inspection.isFulfilled())
        resolved.push(inspection.value());
      else if (inspection.isRejected())
        rejected.push(inspection.reason());
    });

    return [resolved, rejected];
  });

  resolvedAndRejected.spread((resolved, rejected) => {
    console.log(...resolved);
    console.error(...rejected);
  });

It seems like a trivial task for cases where 100% execution speed is not an option or a goal, but I don’t even know the name for the recipe.

Is there a neat and proven way to handle this in Bluebird or other promise implementations — a built-in statement or extension?

+2
source share
3 answers

, . :

 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
   ]);
+4

, reduce :

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

Promise.all(), Promise, return reason .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)
});
Hide result
+1

Source: https://habr.com/ru/post/1662178/


All Articles