Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Created July 2, 2014 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briancavalier/4dda76f87f87a6dbfa9f to your computer and use it in GitHub Desktop.
Save briancavalier/4dda76f87f87a6dbfa9f to your computer and use it in GitHub Desktop.
Find left-most fulfilled promise
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