javascript - 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
})
解决方案
这种类型的逻辑最简单,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();
});
}
推荐阅读
- asp.net - 为什么我在反应中获取会话时没有得到会话?
- xml - 如何使用 Maven 将 jaxb 添加到 Eclipse
- flutter - Flutter - 在颤动中更改时区后未触发本地通知
- html - 在html中按要求制作列
- php - 使用 Cronjob 在后端环境中生成 Typolink
- python-3.x - 使用 Folium 生成地图时修改 geojson tooltip 格式
- android - AsyncLayoutInflater 不适用于 ImageView
- sonarqube - 如何使用 sonarQube 扫描仪扫描 Raml 文件
- php - 如何将 api 平台配置为每个模块中的所有实体都有一个前缀?
- python - lambda function with rank