Break the dynamic sequence of promises into Q

I have several promises (P1, P2, ... Pn) I would like to link them in a sequence (so Q.all is not an option), and I would like to break the chain into the first error.
Each promise comes with its own parameters.
And I would like to catch every promise error in order to make a mistake.

If P1, P2, .. PN are my promises, I don’t know how to automate the sequence.

+6
source share
1 answer

If you have a chain of promises, all of them have already started, and you can’t do anything to start or stop any of them (you can cancel, but as much as possible).

Assuming you return the functions F1,... Fn , you can use the basic building block 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 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, a 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 }); 
+3
source

Source: https://habr.com/ru/post/970943/


All Articles