2016-02-13 67 views
2

我想有一系列的同步執行的承諾,鏈接在一起,但只有具有一定的承諾基礎上增加了一個條件中..的同期鏈藍鳥共同承諾一系列

繼承人的一個例子是我意思是:

const Promise = require('bluebird') 

const funcA = int => new Promise(res => res(++int)) 
const funcB = int => new Promise(res => res(++int)) 
const funcC = int => new Promise(res => res(++int)) 

let mainPromise = funcA(1) 

// Only execute the funcB promise if a condition is true 
if(true) 
    mainPromise = mainPromise.then(funcB) 

mainPromise = mainPromise.then(funcC) 

mainPromise 
    .then(result => console.log('RESULT:',result)) 
    .catch(err => console.log('ERROR:',err)) 

如果布爾爲真,則輸出爲:RESULT: 4,如果假的,那麼它的​​,而這正是我試圖完成。

我覺得應該有更好,更乾淨的方法來做到這一點。我正在使用藍鳥承諾庫,它非常強大。我試着用Promise.join,這並沒有產生預期的結果,我也沒有Promise.reduce(不過,我可能一直在做一個不正確地)

感謝

+0

你能告訴我們您如何使用'Promise.reduce'? – Bergi

+0

只是一個挑逗,但[承諾沒有執行](http://stackoverflow.com/a/30823708/1048572) – Bergi

+0

你想評估'funcA()'解決時的情況,或者是靜態地知道什麼時候構建鏈(如你的例子)?或者沒有關係? – Bergi

回答

0

我找到了一個好的相關線程here。使用相同的邏輯,我能得到這個工作:

const Promise = require('bluebird') 

const funcA = int => new Promise(res => res(++int)) 
const funcB = int => new Promise(res => res(++int)) 
const funcC = int => new Promise(res => res(++int)) 

const toExecute = [funcA, funcB] 

if(!!condition) 
    toExecute.push(funcC) 

Promise.reduce(toExecute, (result, currentFunction) => currentFunction(result), 1) 
    .then(transformedData => console.log('Result:', transformedData)) 
    .catch(err => console.error('ERROR:', err)) 

相同的結果張貼在我原來的線程

1

你鏈接異步函數。把承諾看作是回報價值,不是那麼令人興奮。

你可以把功能在這樣一個數組,然後過濾數組:

[funcA, funcB, funcC] 
    .filter(somefilter) 
    .reduce((p, func) => p.then(int => func(int)), Promise.resolve(1)) 
    .catch(e => console.error(e)); 

或者,如果你只是尋找一個更好的方式與順序條件下寫的,你可以這樣做:

funcA(1) 
    .then(int => condition ? funcB(int) : int) 
    .then(funcC); 
    .catch(e => console.error(e)); 

如果你正在使用ES7則可以使用異步功能:

async function foo() { 
    var int = await funcA(1); 
    if (condition) { 
    int = await funcB(int); 
    } 
    return await funcC(int); 
} 
+0

或者,他可能想要'.then(condition?funcB:(int => int))' – Bergi

+0

這也可以。 – jib

+0

對,我知道它們是異步的,我的意思是我希望承諾以特定的順序執行,並將解析後的數據從一個傳遞到另一個。 - 對於你的第一個例子,它只會將'func *'推向數組,而不是使用過濾器的權利?有沒有辦法爲第一個參數定義一個參數? – Justin