【发布时间】:2014-08-07 07:44:01
【问题描述】:
我有几个承诺 (P1, P2, ... Pn) 我想将它们按顺序链接起来(所以 Q.all 不是一个选项),我想首先打破这个链错误。
每个 Promise 都有自己的参数。
而且我想拦截每一个promise错误来转储错误。
如果 P1、P2、.. PN 是我的承诺,我不知道如何自动化序列。
【问题讨论】:
标签: javascript promise q
我有几个承诺 (P1, P2, ... Pn) 我想将它们按顺序链接起来(所以 Q.all 不是一个选项),我想首先打破这个链错误。
每个 Promise 都有自己的参数。
而且我想拦截每一个promise错误来转储错误。
如果 P1、P2、.. PN 是我的承诺,我不知道如何自动化序列。
【问题讨论】:
标签: javascript promise q
如果你有一连串的承诺,它们都已经开始了,你无法启动或停止其中任何一个(你可以取消,但仅此而已)。
假设您有F1,... Fn promise 返回函数,您可以使用基本的promise 构建块,我们的.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
});
【讨论】:
return accum.then(cur); 之前)创建一个数组,然后 .return 结果。