You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Brian Cavalier edited this page Jul 2, 2014
·
3 revisions
Competitive races like when.any and when.race are primarily for determining the first promise to fulfill or reject in time order (a.k.a. "causal order"). If you need to find the first promise to fulfill in array index order, you can use recursion, similar to the following:
// Returns the fulfilled promise with the lowest array index.// If all promises in the array reject, returns a rejected promise// whose reason is an Error with an `.errors` Array property containing// all the rejection reasons.functionfindFirst(promises){returnrecurseFindFirst(0,[],promises);}functionrecurseFindFirst(i,errors,promises){if(i===promises.length){vare=newError('All promises rejected');e.errors=errors;returnwhen.reject(e);}returnwhen(promises[i]).catch(function(e){errors.push(e);returnrecurseFindFirst(i+1,errors,promises);});}
Here's an example usage. Note that this logs 'c', since it has a lower index that 'd', even though 'd' fulfills first in time. In contrast, when.any would log 'd', and when.race would reject with Error('a').