我正在努力弄清楚如何异步执行多个级别的promises。我已经搜索了文档,但大多数承诺库让你等待所有承诺做一些逻辑或一个然后下一个。我需要这两方面的一个方面。我写了一个快速演示我想要实现的目标。
这背后的一般想法是我需要调用4个函数。 A& B可以立即同时呼叫。 C取决于B的回归。然后我需要所有三个(A,B,C)来计算D.我将如何构建它?
我试图在这里绘制一般流程图:
A -> -> D
B -> C ->
示例代码:
var bluebird = require('bluebird');
function a(){
setTimeout(function(){
console.log('a called');
return 'a';
},1000);
}
function b(){
setTimeout(function(){
console.log('b called');
return 'b message';
},1000);
}
function c(bMessage){
setTimeout(function(){
console.log('c called');
return 'c set in motion';
},1000);
}
function d(aMessage, bMessage, cMessage){
setTimeout(function(){
console.log('prmoises: called: ' + aMessage + bMessage + cMessage);
return 'this the end';
},1000);
}
function test(){
// what goes here?
}
test();
答案 0 :(得分:2)
从returning promises from your asynchronous functions开始,而不只是致电setTimeout
。最好只需完全删除setTimeout
并使用Promise.delay(…).then(…)
。
然后将then
用于单个依赖项,将Promise.join
用于多个依赖项。不要建立长链,在变量中存储您需要的每个结果的承诺:
function test(){
var aPromise = a();
var bPromise = b();
var cPromise = bPromise.then(c);
return Promise.join(aPromise, bPromise, cPromise, d);
}
另请参阅相关问题How do I access previous promise results in a .then() chain?。