我想并行运行异步事物的动态列表,其中一些事情需要先完成其他事情,然后才能访问所有聚合结果。到目前为止,我想出了迭代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}
]
]
是否有一些很好的方法来映射依赖与promises?能够做到这样的事情会很好:
makePotion: [getPixieDust, getMandrake]
然后将整个事情传递给知道getPixieDust的东西,并且在调用makePotion之前先完成getMandrake。而不是仅将相关操作放在后面的数组中的当前实现
答案 0 :(得分: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.
});
}