【问题标题】:Break a dynamic sequence of promises with Q用 Q 打破一个动态的承诺序列
【发布时间】:2014-08-07 07:44:01
【问题描述】:

我有几个承诺 (P1, P2, ... Pn) 我想将它们按顺序链接起来(所以 Q.all 不是一个选项),我想首先打破这个链错误。
每个 Promise 都有自己的参数。
而且我想拦截每一个promise错误来转储错误。

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

【问题讨论】:

    标签: javascript promise q


    【解决方案1】:

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

    假设您有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
    });
    

    【讨论】:

    • 谢谢!但是,我想在最后一个“then”中作为参数传递的“聚合结果”是我必须根据自己的方便自己实现的吗?
    • @Guid 这取决于你的 API,我假设每个 Promise 都需要前一个 Promise 的结果(因为你按顺序要求它们)。例如,您可以 - 在外部创建一个数组,并在循环中(return accum.then(cur); 之前)创建一个数组,然后 .return 结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2018-08-05
    • 2019-03-27
    • 2020-02-23
    • 2019-05-10
    • 2017-07-02
    相关资源
    最近更新 更多