我有几个承诺(P1,P2,... Pn)我想将它们按顺序链接起来(所以 Q.all 不是一个选项)并且我想在第一个错误时打破链条。
每个承诺都有其自己的参数。
我想拦截每个承诺错误以转储错误。
如果 P1、P2、.. PN 是我的承诺,我不知道如何自动化该序列。
如果你有一连串的承诺,它们都已经开始了,你无法启动或停止它们中的任何一个(你可以取消,但仅此而已)。
假设你有F1,... Fn
承诺返回函数,您可以使用承诺的基本构建块,我们的.then
为了这:
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
});
因此,注释较少的版本:
var res = promises.reduce(function(accum,cur){ return accum.then(cur); },Q());
res.then(function(res){
// handle success
}).catch(function(err){
// handle failure
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)