用Q打破动态的承诺序列

时间:2014-06-17 10:24:46

标签: javascript promise q

我有几个承诺(P1,P2,...... Pn)我想按顺序连接它们(所以Q.all不是一个选项)我想打破在第一个错误链。
每个承诺都有自己的参数 并且我想拦截每个承诺错误以转储错误。

如果P1,P2,.. PN是我的承诺,我不知道如何自动化序列。

1 个答案:

答案 0 :(得分:3)

如果你有一连串的承诺,他们都已经开始了,你无法做任何事情来开始或停止他们(你可以取消,但就这一点而言)

假设你有F1,... Fn 承诺返回函数,你可以使用promises的基本构建块,我们的.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
});
相关问题