用Q打破动态的承诺序列 [英] Break a dynamic sequence of promises with Q

查看:92
本文介绍了用Q打破动态的承诺序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个承诺(P1,P2,...... Pn)我想将它们按顺序连接起来(所以Q.all不是一个选项)我想在第一个时打破链条错误。

每个promise都有自己的参数。

我想拦截每个promise错误来转储错误。

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.

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

If P1, P2, .. PN are my promises, I don't have a clue how to automate the sequence.

推荐答案

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

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).

假设您有 F1,... Fn 承诺返回功能,您可以使用基本建筑承诺块,我们的 .then 为此:

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

这篇关于用Q打破动态的承诺序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆