Last active
July 22, 2016 15:56
-
-
Save scottrippey/efc3da511aee9d404c6215a7a4ef86e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Waits for an array of promises to finish, and returns an array of the results. | |
* | |
* If one or more Promises are rejected, throws a RejectionCollection. | |
* | |
* This is very similar to `Promise.all`, except it throws ALL errors, instead of just the FIRST error. | |
* | |
* @param {Array<Promise<T>>} promises | |
* @throws {RejectionCollection} | |
* @return {Promise<Array<T>>} | |
*/ | |
function allSettled(promises) { | |
return new Promise(function(resolve, reject) { | |
var results = new Array(promises.length); | |
var remaining = promises.length; | |
var errors; | |
if (!promises.length) | |
return resolve(results); | |
promises.forEach(function(promise, index) { | |
promise.then(function(result) { | |
results[index] = result; | |
checkIfAllSettled(); | |
}, function(error) { | |
if (!errors) errors = new RejectionCollection(); | |
errors.push(error); | |
checkIfAllSettled(); | |
}); | |
}); | |
function checkIfAllSettled() { | |
if (--remaining) return; | |
if (!errors) { | |
resolve(results); | |
} else { | |
reject(errors); | |
} | |
} | |
}); | |
} | |
function RejectionCollection() { } | |
RejectionCollection.prototype = Object.assign(new Error(), { | |
name: "RejectionCollection", | |
push: Array.prototype.push, | |
forEach: Array.prototype.forEach, | |
toArray: Array.prototype.slice | |
}); | |
module.exports = allSettled; | |
module.exports.RejectionCollection = RejectionCollection; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var allSettled = require("./allSettled.js"); | |
async function doParallelStuff() { | |
var async1 = Promise.reject(new Error("Error One")); | |
var async2 = Promise.reject(new Error("Error Two")); | |
var async3 = Promise.resolve("This one is OK!"); | |
try { | |
var results = await allSettled([ async1, async2, async3 ]) | |
} catch (errors) { | |
for (let error of errors) { | |
console.log(error.message); | |
} | |
/* Logs: | |
* "Error One" | |
* "Error Two" | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment