2015-12-14 35 views
1

我想做條件那麼在承諾(藍鳥)

getFoo() 
    .then(doA) 
    .then(doB) 
    .if(ifC, doC) 
    .else(doElse) 

我認爲的代碼是很明顯?無論如何:

我想給一個承諾,當一個特定的條件(也是一個承諾)給出。我大概可以做一些像

getFoo() 
    .then(doA) 
    .then(doB) 
    .then(function(){ 
    ifC().then(function(res){ 
    if(res) return doC(); 
    else return doElse(); 
    }); 

但是,這感覺很詳細。

我使用藍鳥作爲承諾庫。但我猜如果有這樣的事情,它會在任何承諾庫中都是一樣的。

回答

4

你並不需要嵌套調用.then,因爲它看起來像ifC返回Promise反正:

getFoo() 
    .then(doA) 
    .then(doB) 
    .then(ifC) 
    .then(function(res) { 
    if (res) return doC(); 
    else return doElse(); 
    }); 

你也可以做一些跑腿前面:

function myIf(condition, ifFn, elseFn) { 
    return function() { 
    if (condition.apply(null, arguments)) 
     return ifFn(); 
    else 
     return elseFn(); 
    } 
} 

getFoo() 
    .then(doA) 
    .then(doB) 
    .then(ifC) 
    .then(myIf(function(res) { 
     return !!res; 
    }, doC, doElse)); 
2

我想你正在尋找的東西像this

一個例子與您的代碼:

getFoo() 
    .then(doA) 
    .then(doB) 
    .then(condition ? doC() : doElse()); 

條件中的元素必須在啓動鏈之前定義。

0

基於this other question,這裏就是我想出了一個可選的,則:

注意:如果你的病情功能真正需要的是一個承諾,看看@ TbWill4321的回答

答案爲可選then()

getFoo() 
    .then(doA) 
    .then(doB) 
    .then((b) => { ifC(b) ? doC(b) : Promise.resolve(b) }) // to be able to skip doC() 
    .then(doElse) // doElse will run if all the previous resolves 

改進答案˚F ROM @jacksmirk爲條件then()

getFoo() 
    .then(doA) 
    .then(doB) 
    .then((b) => { ifC(b) ? doC(b) : doElse(b) }); // will execute either doC() or doElse() 

編輯:我建議你看看藍鳥的討論在具有promise.if()HERE