用Q打破动态的承诺序列

Gui*_*uid 6 javascript promise q

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

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

Ben*_*aum 3

如果你有一连串的承诺,它们都已经开始了,你无法启动或停止它们中的任何一个(你可以取消,但仅此而已)。

假设您有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
});
Run Code Online (Sandbox Code Playgroud)

因此,注释较少的版本:

var res = promises.reduce(function(accum,cur){ return accum.then(cur); },Q());

res.then(function(res){
   // handle success
}).catch(function(err){
   // handle failure
});
Run Code Online (Sandbox Code Playgroud)