crazy4groovy
10/17/2016 - 8:12 PM

A strategy to try a list of promises, and then check which ones were resolved (or rejected).

A strategy to try a list of promises, and then check which ones were resolved (or rejected).

var promises = [];
var cnt = 0;

function makePromises() {
  console.log('make', Date.now())
  promises.length = 0; // clear array
  promises.push(new Promise((resolve, reject) => setTimeout(resolve, 1000, `Everything OK in Promise ${cnt++}`))); 
  promises.push(new Promise((resolve, reject) => setTimeout(resolve, 2000, `Everything OK in Promise ${cnt++}`)));
  promises.push(new Promise((resolve, reject) => reject(new Error(`Something went wrong in Promise ${cnt++}`))));
  return promises;
}

function resolveRejectify (promise) {
  return promise
  .then(resolved => ({ resolved }))
  .catch(rejected => ({ rejected }));
}

function checkResults(promiseResults) {
  console.log('check', Date.now())
  promiseResults.forEach((result) => {
    if (result.rejected) console.error(`ERR: ${result.rejected.message}`);
    else console.log(result.resolved);
  });
}

Promise.all(makePromises().map(resolveRejectify))
.then(checkResults)
.then(
  Promise.all(makePromises().map(resolveRejectify))
  .then(checkResults)
).then(
  Promise.all(makePromises().map(resolveRejectify))
  .then(checkResults)
);