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

How to handle conditional callbacks using Promises(Bluebird) in NodeJS

我目前正在尝试重构我拥有的代码库,并希望拥有一个对开发人员更友好的代码库。第 1 部分是将回调更改为 Promises。目前,在某些地方,我们正在使用 Async.waterfall 来平息回调地狱,这对我很有用。剩下的地方我们不能是因为它们是条件回调,这意味着 if 和 else

内部的回调函数不同
if(x){
    call_this_callback()
}else{
    call_other_callback()
}

现在我在 Node.JS 中将 bluebird 用于 promises,但我不知道如何处理条件回调以平息回调地狱。

编辑 一个更现实的场景,考虑到我没有抓住问题的关键。

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

没有魔法,您可以轻松地将承诺与承诺中的 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
});

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

这是 promise 分支的 :嵌套和非嵌套。 做树枝,不要把它们连在一起。