Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Created July 2, 2014 14:51
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/33c346b478e8f36c1076 to your computer and use it in GitHub Desktop.
Save briancavalier/33c346b478e8f36c1076 to your computer and use it in GitHub Desktop.
Simplified find left-most fulfilled
function findFirst(promises){
return recurseFindFirst(0, [], promises);
}
function recurseFindFirst(i, errors, promises) {
if(i === promises.length) {
var e = new Error('All promises rejected');
e.errors = errors;
return when.reject(e);
}
return when(promises[i]).catch(function(e) {
errors.push(e);
return recurseFindFirst(i+1, errors, promises);
});
}
var testList = [
when.reject(new Error('a')),
when.reject(new Error('b')),
when.resolve('c'),
when.reject(new Error('d'))
];
findFirst(testList).done(console.log.bind(console));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment