2015-12-14 102 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