-
-
Save briancavalier/4dda76f87f87a6dbfa9f to your computer and use it in GitHub Desktop.
Find left-most fulfilled promise
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
function findFirst(promises){ | |
return when(promises).then(function(promises) { | |
return recurseFindFirst(0, [], promises); | |
}); | |
} | |
function recurseFindFirst(i, errors, promises) { | |
if(i === promises.length) { | |
return when.reject(new AggregateError('All promises rejected', errors)); | |
} | |
return when(promises[i]).catch(function(e) { | |
errors.push(e); | |
return recurseFindFirst(i+1, errors, promises); | |
}); | |
} | |
function AggregateError(msg, errors) { | |
Error.call(this); | |
this.errors = errors; | |
this.message = msg; | |
if(Error.captureStackTrace) { | |
Error.captureStackTrace(this, AggregateError); | |
} | |
} | |
AggregateError.prototype = Object.create(Error.prototype); | |
AggregateError.prototype.constructor = AggregateError; | |
var testList = [ | |
when.reject('a'), | |
when.reject('b'), | |
when.resolve('c'), | |
when.reject('d') | |
]; | |
findFirst(testList).done(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment