Skip to content

First fulfilled promise by array order

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.
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);
	});
}

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').

var testList = [
	when.reject(new Error('a')),
	when.reject(new Error('b')),
	when.resolve('c').delay(1000),
	when.resolve('d')
];

findFirst(testList).done(console.log.bind(console)); // Logs 'c'
Clone this wiki locally