2017-09-14 103 views
1

我被承諾卡住了。如何創建一個類似於鑽石的js承諾鏈

說我的程序結構是這樣的

  Func A    //gets data then passes to I1 and J2 
     /  \ 
     Func I1  Func J1  //then route I & J run without interaction 
     |   | 
     Func I2  Func J2  
     \  /
      Func B   //Func B gets both the result of both 

我有一點麻煩這個工作。 我只要

getdata.then(data=>{ 
     var methods = Promise.all([ 
     funci1.x(data).then(output=>{ 
      funci2.x(output) 
     }), 
     funcj1.x(data).then(output2=>{ 
      funcj2.x(output2) 
     }) 
     ]) 
     methods.then(([a,b])=>{ 
     console.log(a,b); 
     }) 
    }) 

但它似乎並沒有工作。任何幫助?

+1

主要問題是您使用箭頭功能。爲了澄清,'()=> {...}'執行花括號內的代碼,並且只有在有明確的'return'語句時才返回一個值。 '()=>語句'另一方面隱式返回'語句'的結果 – Phil

+0

看起來更像一個梯形(辛普森參考) –

回答

3

你不回任何可以在你的兩個then()回調被澆鑄爲Promise,所以改成這樣:

getdata.then(data => { 
    var methods = Promise.all([ 
    funci1.x(data).then(output => funci2.x(output)), 
    funcj1.x(data).then(output2 => funcj2.x(output2)) 
    ]) 
    methods.then(([a, b]) => { 
    console.log(a, b); 
    }) 
}) 
+0

可能要指出的差異,因爲它是非常微妙的 – Phil

1

我個人覺得承諾寫成這樣更容易識別是怎麼回事。

const funcJ1 = (num) => { 
    num = num + 1; 
    return funcJ2(num); 
} 
const funcJ2 = (num) => (
    new Promise((resolve, reject) => { 
    num = num + 1; 
    resolve(num); 
    }) 
); 

const funcI1 = (num) => { 
    num = num + 1; 
    return funcI2(num); 
} 
const funcI2 = (num) => (
    new Promise((resolve, reject) => { 
    num = num + 1; 
    resolve(num); 
    }) 
); 

const funcB = (result) => { 
    let total = 0; 
    total = total + result[0]; // first promise result 
    total = total + result[1]; // second promise result 
    console.log(total); 
}; 

const funcA = (x) => { 
    const promises = []; 
    promises.push(funcJ1(x)); 
    promises.push(funcI2(x)); 
    Promise.all(promises).then((res) => { 
     funcB(res); // done with I and J 
    }).catch((e) => { 
     throw e; 
    }); 
} 

funcA(1); 

funcJ1和funcI1都將並行運行,funcB將在funcJ2和funcI2完成後運行。

看到這個jsfiddle https://jsfiddle.net/6fvLw8wv/

+0

我如何得到j1和i1從func a的數據運行一個 – Harryw

+0

我已經修改並添加了一個參數傳遞給funcA。希望有所幫助。 – dmo