Break a dynamic sequence of promises with Q

强颜欢笑 提交于 2019-12-10 13:08:11

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/24261379/break-a-dynamic-sequence-of-promises-with-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!