Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Promise.any
// Promises are started in parallel.
// Resolves with the first resolved value in time.
// If there's no winner, it rejects with last rejection.
Promise.any = function (promises) {
return new Promise((resolve, reject) => {
var rejectedCount = 0;
function onMemberResolved(value) {
resolve(value);
}
function onMemberRejected(reason) {
if (++rejectedCount == promises.length)
reject(reason);
}
function observeSettled(promise) {
promise.then(onMemberResolved)
.catch(onMemberRejected);
}
promises.forEach(observeSettled);
});
};
Promise.fastest = Promise.any;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment