If you want the first promise to be successfully resolved, and you want to ignore any deviations that were before, you can use something like this:
// returns the result from the first promise that resolves // or rejects if all the promises reject - then return array of rejected errors function firstPromiseResolve(array) { return new Promise(function(resolve, reject) { if (!array || !array.length) { return reject(new Error("array passed to firstPromiseResolve() cannot be empty")); } var errors = new Array(array.length); var errorCntr = 0; array.forEach(function (p, index) { // when a promise resolves Promise.resolve(p).then(function(val) { // only first one to call resolve will actually do anything resolve(val); }, function(err) { errors[index] = err; ++errorCntr; // if all promises have rejected, then reject if (errorCntr === array.length) { reject(errors); } }); }); }); }
I donβt see how you can use Promise.race() for this, because it simply reports the first promise to finish, and if this first promise is rejected, it will report a refusal. Thus, he does not do what you asked in your question, which should report the first promise that resolves (even if some refusals have ended before him).
FYI, the Bluebird promise library has both Promise.some() and Promise.any() that can handle this case for you.
source share