How to handle the if-else in promise then?

后端 未结 3 1715
旧时难觅i
旧时难觅i 2020-12-04 09:36

In some case, when I get a return value from a promise object, I need to start two different then() precesses depend on the value\'s condition, like:

         


        
3条回答
  •  遥遥无期
    2020-12-04 10:00

    As long as your functions return a promise, you can use the first method that you suggest.

    The fiddle below shows how you can take different chaining paths depending on what the first resolved value will be.

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

    You can also just make one conditional chaining, assign the return promise to a variable and then keep executing the functions that should be run either way.

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

提交回复
热议问题