NodeJS Promise Chaining:重用 "then" 并合并两个 promise
NodeJS Promise Chaining: reuse "then" and merge two promises
我有 2 个具有相同 "then" 和 "catch" 条件的承诺。我如何根据条件将它们合并为单一承诺?
承诺 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);
});
});
需要 Promise 链
return new Promise((resolve, reject) => {
if(condition){
abc.getDataFromServer(resp)
}else{
abc.getDataFromDB(resp2)
}
.then((result) => {
.....
resolve();
})
.catch((error) => {
.....
reject(error);
});
});
实现此目标的最佳方法是什么?
使用条件运算符,根据condition
,确定初始的Promise
,然后在其上调用.then
和.catch
。另外,避免 explicit Promise construction antipattern:
return (condition ? abc.getDataFromServer(resp) : abc.getDataFromDB(resp2))
.then((result) => {
.....
// instead of resolve(someTransformedResult):
return someTransformedResult;
})
.catch((error) => {
.....
// instead of reject(error):
throw error;
});
我有 2 个具有相同 "then" 和 "catch" 条件的承诺。我如何根据条件将它们合并为单一承诺?
承诺 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);
});
});
需要 Promise 链
return new Promise((resolve, reject) => {
if(condition){
abc.getDataFromServer(resp)
}else{
abc.getDataFromDB(resp2)
}
.then((result) => {
.....
resolve();
})
.catch((error) => {
.....
reject(error);
});
});
实现此目标的最佳方法是什么?
使用条件运算符,根据condition
,确定初始的Promise
,然后在其上调用.then
和.catch
。另外,避免 explicit Promise construction antipattern:
return (condition ? abc.getDataFromServer(resp) : abc.getDataFromDB(resp2))
.then((result) => {
.....
// instead of resolve(someTransformedResult):
return someTransformedResult;
})
.catch((error) => {
.....
// instead of reject(error):
throw error;
});