如何在NodeJS中使用Promises(Bluebird)处理条件callback

我目前正试图重构我拥有的代码库,并希望有一个更开发人员友好的代码库。 第一部分正在改变对Promise的callback。 目前,在一些地方,我们正在使用Async.waterfall来压扁callback地狱,这对我很有用。 其余的地方,我们不能是因为他们是有条件的callback,这意味着不同的callback函数里面的if和else

if(x){ call_this_callback() }else{ call_other_callback() } 

现在我在Node.JS中使用蓝鸟作为承诺,我无法弄清楚如何处理有条件的callback来压扁callback地狱。

编辑一个更现实的场景,考虑到我没有得到这个问题的症结所在。

 var promise = Collection1.find({ condn: true }).exec() promise.then(function(val) { if(val){ return gotoStep2(); }else{ return createItem(); } }) .then(function (res){ //I don't know which response I am getting Is it the promise of gotoStep2 //or from the createItem because in both the different database is going //to be called. How do I handle this }) 

没有魔法,你可以很容易地将诺言与承诺联系起来。

 var promise = Collection1.find({ condn: true }).exec(); //first approach promise.then(function(val) { if(val){ return gotoStep2() .then(function(result) { //handle result from gotoStep2() here }); }else{ return createItem() .then(function(result) { //handle result from createItem() here }); } }); //second approach promise.then(function(val) { return new Promise(function() { if(val){ return gotoStep2() } else { return createItem(); } }).then(function(result) { if (val) { //this is result from gotoStep2(); } else { //this is result from createItem(); } }); }); //third approach promise.then(function(val) { if(val){ return gotoStep2(); //assume return array } else { return createItem(); //assume return object } }).then(function(result) { //validate the result if it has own status or type if (Array.isArray(result)) { //returned from gotoStep2() } else { //returned from createItem() } //you can have other validation or status checking based on your results }); 

编辑:更新示例代码,因为作者更新了他的示例代码。 编辑:增加第三种方法来帮助你理解承诺链

这是promise分支的答案 :嵌套和unnested。 做分支,不要一起join。