Given this pattern
someArray.reduce(function(p, item) {
return p.then(function() {
return someFunction(item);
});
}, $.Deferred().resolve()).then(fun
There are multiple possible strategies depending upon the specifics of what you're trying to do: Here's one option:
someArray.reduce(function(p, item) {
return p.then(function(array) {
return someFunction(item).then(function(val) {
array.push(val);
return array;
});
});
}, $.Deferred().resolve([])).then(function(array) {
// all done here
// accumulated results in array
}, function(err) {
// err is the error from the rejected promise that stopped the chain of execution
});
Working demo: http://jsfiddle.net/jfriend00/d4q1aaa0/
FYI, the Bluebird Promise library (which is what I generally use) has .mapSeries()
which is built for this pattern:
var someArray = [1,2,3,4];
Promise.mapSeries(someArray, function(item) {
return someFunction(item);
}).then(function(results) {
log(results);
});
Working demo: http://jsfiddle.net/jfriend00/7fm3wv7j/