2016-11-30 83 views
1

我目前正试图重构我拥有的代码库,并希望拥有更开发人员友好的代码库。第一部分正在改变对Promises的回调。目前,在一些地方,我们使用Async.waterfall来压扁回调地狱,这对我很有用。我们不能,是因为他们是有条件的回调余缺,这意味着内部不同的回调函数if和else如何在NodeJS中使用Promises(Bluebird)处理条件回调

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

现在我用的蓝鸟在node.js中的承诺,我无法弄清楚如何处理有条件的回调来平抑回调地狱。

编辑 更现实的情况下,考虑到我没有得到问题的关键。

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 
}) 

回答

2

没有什么魔力,你可以很容易地将诺言与return链接起来。

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 
}); 

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

+0

在这里你正在使用三个回调函数..将被称为? –

+0

我刚刚编辑了这个问题。使情景更具说明性,你能否编辑你的答案来反映这一点。 –

+0

我发现的第一种方法是令人沮丧,因为它促进了回调中的回调,这是我不想要的。第二个是更通用的方法,需要使用闭包,在那里我需要确保在所有连续链接函数中都有不同的变量。第三个适用于从两个不同函数中获取不同数据类型的情况。他们中没有一个似乎足够通用,但会在这个时间点完成。将继续寻找更优雅的解决方案。如果找到将更新它。谢谢你的时间。非常感激。 –

0

以下是承诺分支的answer:嵌套和unnested。 制作分支,不要将它们连接在一起。

+0

这是一个很长的回答和问题。 @jiajianrong我会看看实施情况,明天就此回复。 –