首页 > 解决方案 > Node js 中的条件承诺

问题描述

如何在没有嵌套承诺的情况下调用条件承诺并执行其余代码,而不管条件是否满足

        findAllByServiceProviderLocationId(serviceProviderLocationId, supplierId)
    .then(result => {
    // 1. set all the default values
    ChargesAdminController._setDefaultValues(result);
    //Based on some condition in result - i need to call new promise
    //If condition satisfy, do promise operation and continue executing. is there better way to do apart from nested promise`enter code here`
    //Ex:
    if(result.checkPricing){
        DBConnection.getPricing(result)
     }
        //some operations on result object before sending response - All these operations should run only after the conditional promise is fulfilled 
    })

标签: javascriptnode.js

解决方案


这种类型的逻辑最简单,async/await因为您可以编写更传统的顺序代码流逻辑。

async function myFunc() {
    let result = await someFunc1();
    if (result.whatever === something) {
         // asynchronous operation inside the if statement
         await someFunc2();
    }
    // code here that gets executed regardless of the above if
    let someOtherResult = await someFunc3();
    return someResult;
}

没有async/await你必须做一些嵌套,但仅限于条件:

function myFunc() {
    return someFunc1().then(result => {
        if (result.whatever === something) {
            // asynchronous operation inside the if statement
            return someFunc2();
        } else {
            return somethingElse;
        }
    }).then(thing => {
        // code here that gets executed regardless of the above if statement
        return someFunc3();
    });
}

推荐阅读