那么如何处理if-else的承诺呢?

Bri*_*ang 71 asynchronous node.js promise

在某些情况下,当我从promise对象获得返回值时,我需要then()根据值的条件启动两个不同的precesses,例如:

promise().then(function(value){
    if(//true) {
        // do something
    } else {
        // do something 
    }
})
Run Code Online (Sandbox Code Playgroud)

我想也许我可以这样写:

promise().then(function(value){
    if(//true) {
        // call a new function which will return a new promise object
        ifTruePromise().then();
    } else {
        ifFalsePromise().then();
    }
})
Run Code Online (Sandbox Code Playgroud)

但有了这个,我有两个问题:

  1. 我不确定在承诺中开始一个新的承诺 - 然后处理是否是一个好主意;

  2. 如果我需要两个进程在最后调用一个函数怎么办?这意味着他们拥有相同的"终端"

我试图回复新的承诺,保持原来的链:

promise().then(function(value){
    if(//true) {
        // call a new function which will return a new promise object
        // and return it
        return ifTruePromise();
    } else {
        // do something, no new promise
        // hope to stop the then chain
    }
}).then(// I can handle the result of ifTruePromise here now);
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,无论是真还是假,下一步then都会奏效.

那么,处理它的最佳做法是什么?

Dan*_*l B 48

只要您的函数返回一个承诺,您就可以使用您建议的第一种方法.

下面的小提示显示了如何根据第一个解析的值来采用不同的链接路径.

function myPromiseFunction() {
	//Change the resolved value to take a different path
    return Promise.resolve(true);
}

function conditionalChaining(value) {
    if (value) {
        //do something
        return doSomething().then(doSomethingMore).then(doEvenSomethingMore);
    } else {
        //do something else
        return doSomeOtherThing().then(doSomethingMore).then(doEvenSomethingMore);
    }
}

function doSomething() {
    console.log("Inside doSomething function");
    return Promise.resolve("This message comes from doSomeThing function");
}

function doSomeOtherThing() {
    console.log("Inside doSomeOtherthing function");
    return Promise.resolve("This message comes from doSomeOtherThing function");
}

function doSomethingMore(message) {
    console.log(message);
    return Promise.resolve("Leaving doSomethingMore");
}

function doEvenSomethingMore(message) {
    console.log("Inside doEvenSomethingMore function");
    return Promise.resolve();
}

myPromiseFunction().then(conditionalChaining).then(function () {
    console.log("All done!");
}).
catch (function (e) {

});
Run Code Online (Sandbox Code Playgroud)

您也可以只进行一次条件链接,将返回承诺分配给变量,然后继续执行应该以任一方式运行的函数.

function conditionalChaining(value){
    if (value) {
        //do something
        return doSomething();
    } else{
        //do something else
        return doSomeOtherThing();
    }
}

var promise = myPromiseFunction().then(conditionalChaining);

promise.then(function(value){
    //keep executing functions that should be called either way
});
Run Code Online (Sandbox Code Playgroud)