Last active
November 10, 2015 16:41
-
-
Save ssoper/35cee246acdac7745d04 to your computer and use it in GitHub Desktop.
Extension for Promises which gets the result of the first Promise that passes
This file contains 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
/** | |
* Promise.first | |
* Get the result of the first Promise that passes | |
* If none of the Promises pass then it is rejected | |
* Doesn’t short-circuit like Promise.race | |
* Requires ES6 | |
*/ | |
if (Promise.first === undefined) { | |
Promise.first = (promises) => { | |
return new Promise((resolve, reject) => { | |
var counter = 0; | |
var result; | |
var done = function(err, value) { | |
counter++; | |
if (value && result === undefined) { | |
result = value; | |
} | |
if (counter === promises.length) { | |
if (result) { | |
return resolve(result); | |
} | |
reject(err); | |
} | |
} | |
for (var promise of promises) { | |
promise.then((value) => { | |
done(null, value) | |
}, (reason) => { | |
done(reason); | |
}); | |
} | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment