【问题标题】:Clean way of keeping an aggregate of a sequence of Q.all promises [duplicate]保持 Q.all 承诺序列聚合的干净方式[重复]
【发布时间】:2014-03-20 13:39:07
【问题描述】:

我想在执行一系列Q.all 任务时维护中间结果的聚合。

具体问题如下:

var Obj = function(first, second) { 
    return { 
        stuff: first, 
        otherStuff: [1,2],
        nextStuff: function() { return Q.fcall(function() { return second }) }
    }
};                                     

var ab = Q.fcall(function() { return Obj("A", "B"); });
var cd = Q.fcall(function() { return Obj("C", "D"); });

var promises = [ab, cd];

我想要的是[{stuff: obj, nextStuff: "B"}, {stuff: obj, nextStuff: "D"}]的结果

现在我保留对先前结果的引用并使用 underscore.js 映射它们

Q.all(promises).then(function(stuffs) { 
    var promiseNextStuff = _.map(stuffs, function(x) { return x.nextStuff(); });
    Q.all(promiseNextStuff).then(function(nextStuffs) { 
        var result = _.map(_.zip(stuffs, nextStuffs), function(obj) { 
            return _.object(["stuff", "nextStuff"], obj); 
        });
        console.log("result", result);
    });
});

...但我相信 Q 有更好的方法

http://jsfiddle.net/joelkuiper/xY8Ew/2/

【问题讨论】:

  • 不会是stuff: "A"stuff: "C"吗?
  • @Bergi:不,我想要对原始对象的引用,除了“stuff”之外,它可能还有其他字段。我应该说得更清楚!

标签: javascript asynchronous functional-programming promise q


【解决方案1】:

在将结果转换回对象之前,我不会等待所有承诺(或所有 nextStuffPromises):

Q.all(_.invoke(promises, "then", function(obj) {
// or:_.map(promises, function(p) { return p.then(function(obj) {
    return obj.nextStuff().then(function(nextStuff) {
        return {
            prevStuff: obj,
            nextStuff: nextStuff
        };
    }); // });
})).then(console.log.bind(console, "result:"));

除了嵌套 then 调用之外,Q 中没有其他方法可以访问以前的结果。

【讨论】:

  • 啊,是的,干净多了!谢谢:-)
猜你喜欢
  • 2017-04-26
  • 1970-01-01
  • 2016-08-23
  • 1970-01-01
  • 2016-03-04
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
相关资源
最近更新 更多