2016-06-14 90 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