javascript - NodeJS Promise Chaining:重用“then”并合并两个 Promise
问题描述
我有 2 个具有相同“then”和“catch”条件的 promise。如何根据条件将它们合并为单个承诺?
承诺 1
return new Promise((resolve, reject) => {
abc.getDataFromServer(resp1)
.then((result) => {
.....
resolve();
})
.catch((error) => {
.....
reject(error);
});
});
承诺 2
return new Promise((resolve, reject) => {
abc.getDataFromDB(resp2)
.then((result) => {
.....
resolve();
})
.catch((error) => {
.....
reject(error);
});
});
所需的承诺链
return new Promise((resolve, reject) => {
if(condition){
abc.getDataFromServer(resp)
}else{
abc.getDataFromDB(resp2)
}
.then((result) => {
.....
resolve();
})
.catch((error) => {
.....
reject(error);
});
});
实现这一目标的最佳方法是什么?
解决方案
使用条件运算符,基于condition
, 来确定初始Promise
,然后调用.then
and .catch
。另外,避免显式的 Promise 构造反模式:
return (condition ? abc.getDataFromServer(resp) : abc.getDataFromDB(resp2))
.then((result) => {
.....
// instead of resolve(someTransformedResult):
return someTransformedResult;
})
.catch((error) => {
.....
// instead of reject(error):
throw error;
});
推荐阅读
- python - 如何从列表中的键获取字典值?
- javascript - 尝试限制猜测后,javascript(html)while循环不起作用
- c# - 尝试使用 AutoMapper 将 JObject 映射到 c# 类,我得到子元素的 NULL
- jquery - Image-Resize-Crop-imageResizer 在顶级 jquery 插件中不起作用
- android - Android WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS Android Api 级别 30 (Android 11) 不起作用
- mysql - 如何在没有重复行的情况下进行左连接sql
- postgresql - 为什么我不能在这个 where 子句中使用 plsql 参数?
- python-3.x - 如何打印出具有良好输出的字典
- javascript - 如何通过 div 标签而不是使用 JS 的像素隐藏/显示粘性页脚菜单
- angular - Platform.blink 路由,子路由不再起作用