1

我想并行运行异步事物的动态列表,其中有些事情需要先完成其他事情,然后才能访问所有聚合结果。到目前为止,我想出了通过 multidim 迭代。操作数组,但它需要包装函数/闭包,所以我对它并不完全满意。我想知道人们还在为这种情况做些什么。

var runAllOps = function(ops) {
    var all = []; // counter for results

    var runOperations = function runOperations(ops) {
        var set = ops.shift();
        return Promise.map(set, function(op){
            return op.getData.call(null, op.name)
        })
        .then(function(results){
            all.push(results)
            if (ops.length){
                return runOperations(ops)
            } else {
                return _.flatten(all)
            }
        })
    }

    return runOperations(ops)
}

操作如下所示:

var operations = [
    [
        {name: 'getPixieDust', getData: someAsyncFunction},
        {name: 'getMandrake', getData: etc},
    ],
    [
        {name: 'makePotion', getData: brewAsync}
    ]   
] 

有没有一些好的方法来映射依赖关系和承诺?能够像这样会很好:

makePotion: [getPixieDust, getMandrake]

然后将整个事情传递给知道 getPixieDust 和 getMandrake 在调用 makePotion 之前首先完成的事情。而不是当前的实现只是将依赖操作放在后面的数组中

4

1 回答 1

0

目前在 Bluebird 或我知道的任何其他承诺库中没有自动的方法来执行此操作。简单地说 - 你通过自己构建树来做到这一点。

这是我处理这个问题的方法。首先,让我们缓存结果:

var pixieDustP = null;
function getPixieDust(){
    return pixieDustP || (pixieDustP = apiCallReturningPromise());
}

var mandrakeP = null;
function getMandrake(){
    return mandrakeP || (mandrakeP = apiCallReturningPixieDustPromise());
}

function makePotion(){
    return Promise.join(getMandrake(),getPixieDust(),function(dust,mandrake){
        // do whatever with both, this is ok since it'll call them both.
        // this should also probably be cached.
    });
}
于 2014-07-08T17:21:18.173 回答