2016-06-14 91 views
0

我很想弄清楚如何让多级承诺异步执行。我已经通过文档进行了搜索,但是大多数承诺图书馆都在等待所有承诺做出一些逻辑或者接下来的一个逻辑。我需要这两方面的一个方面。我写了一个快速演示我想要达到的目标。蓝鸟承诺多级

背后的一般想法是我有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(); 

回答

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?

+0

谢谢,这回答了我所有的问题! settimeouts只是为了说明我的问题 – lostAstronaut