I basically want to find a specific promise in a given array of promises. The thing is that (I'm using bluebird promises, but the same hold true for anouther standard implementations):
- it is impossible to use just
Promise.some
/Promise.any
, because between resolved values I'm interested in resolved value of a special kind - it is impossible to use
Promise.filter
because array can have rejected values and it is completely OK.
Here's code I'm currently using. I'm OK with it, it works, but had I find anything more elegant it would be nice:
var findPromise = function findPromise(promises, findFunc) {
var rejected = [];
Object.defineProperty(rejected, 'name', {
enumerable: false,
value: 'NOT_FOUND'
});
var step = function step(count, promises) {
if (count < promises.length) {
var promise = promises[count];
return promise.then(function(data) {
if (findFunc(data)) {
return Promise.resolve(data);
} else {
return step(count + 1, promises);
}
}, function(reason) {
rejected.push(reason);
return step(count + 1, promises);
});
} else {
return Promise.reject(rejected);
}
}
return step(0, promises);
}