Last active
November 22, 2016 21:37
-
-
Save gblazex/671e10df0bdc6638b06e20e23542e62d to your computer and use it in GitHub Desktop.
Promise.any
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
// 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