I've got several promises (P1, P2, ... Pn) I would like to chain them in a sequence (so Q.all is not an option) and I'd like to break the chain at the first error.
Every promise comes with its own parameters.
And I'd like to intercept every promise error to dump the error.
If P1, P2, .. PN are my promises, I don't have a clue how to automate the sequence.
If you have a chain of promises, they've all already started and there is nothing you can do to start or stop any of them (you can cancel, but that's as far as it goes).
Assuming you have F1,... Fn
promise returning functions, you can use the basic building block of promises, our .then
for this:
var promises = /* where you get them, assuming array */;
// reduce the promise function into a single chain
var result = promises.reduce(function(accum, cur){
return accum.then(cur); // pass the next function as the `.then` handler,
// it will accept as its parameter the last one's return value
}, Q()); // use an empty resolved promise for an initial value
result.then(function(res){
// all of the promises fulfilled, res contains the aggregated return value
}).catch(function(err){
// one of the promises failed,
//this will be called with err being the _first_ error like you requested
});
So, the less annotated version:
var res = promises.reduce(function(accum,cur){ return accum.then(cur); },Q());
res.then(function(res){
// handle success
}).catch(function(err){
// handle failure
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With