Skip to content

Instantly share code, notes, and snippets.

@ssoper
Last active November 10, 2015 16:41
Show Gist options
  • Save ssoper/35cee246acdac7745d04 to your computer and use it in GitHub Desktop.
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
/**
* 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