Skip to content

Instantly share code, notes, and snippets.

@gblazex
Last active November 22, 2016 21:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gblazex/671e10df0bdc6638b06e20e23542e62d to your computer and use it in GitHub Desktop.
Save gblazex/671e10df0bdc6638b06e20e23542e62d to your computer and use it in GitHub Desktop.
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