【发布时间】:2019-03-10 09:40:19
【问题描述】:
我遇到过多个应用程序,其中使用catch 优于rejectHandler。 例如: 喜欢
new Promise.then(resolveHandler).catch()
而不是
new Promise().then(resolveHandler, rejectHandler).catch()
这有什么特别的原因吗??
我找到了
new Promise().then(resolveHandler, rejectHandler).catch()
更有用,因为
- 我可以使用rejectHandler 来解决调用Promise.reject 的设计/预期错误场景。
- 我可以使用 catch 块来解决发生的未知/意外编程/运行时错误。
有人知道为什么拒绝处理程序没有被大量使用的任何特殊原因吗?
附:我知道 ES6 中有更新的替代品,但我只是想知道这一点。
更新:我知道rejectHandler 和catch 是如何工作的。问题是为什么我看到更多的人只使用catch 而不是rejectHandler 和catch?这是最佳做法还是有一些优势?
更新(在此处添加答案):找到我正在寻找的第一手答案。 原因不仅仅是因为拒绝中的错误是由catch处理的,主要是因为链接。当我们链接promise.then.then.then.then 时,有一个resolve,reject 模式证明链接它有点棘手,因为您不想实现rejecthandler 只是为了将rejectData 转发到链上。仅使用 promise/then/catch 和 resolve/return/throw 在链接 N 个 thenable 时非常有用。 @Bob-Fanger(接受的答案)也解决了其中的一部分问题。 例如:
getData(id) {
return service.getData().then(dataList => {
const data = dataList.find(data => {
return data.id === id;
});
if (!data) {
// If I use Promise.reject here and use a reject handler in the parent then the parent might just be using the handler to route the error upwards in the chain
//If I use Promise.reject here and parent doesn't use reject handler then it goes to catch which can be just achieved using throw.
throw {
code: 404,
message: 'Data not present for this ID'
};
}
return configuration;
});
}
//somewhere up the chain
....getConfiguration()
.then(() => {
//successful promise execution
})
.catch(err => {
if (err.code) {
// checked exception
send(err);
} else {
//unchecked exception
send({
code: 500,
message: `Internal Server error: ${err}`
});
}
});
仅使用这些我需要担心的是 promise/then/catch 以及 resolve/return/throw 在链中的任何位置。
【问题讨论】:
-
“这是最佳实践还是有一些优势?” 只需编写一个函数而不是两个?我认为没有围绕这一点建立最佳实践。我认为人们只是觉得这更容易理解。
-
“这是最佳实践还是有一些优势?” 没有任何技术优势(因此,没有最佳实践)。正如我在回答中所说,这实际上取决于您需要代码来实现什么。
-
P.S.我知道 ES6 中有更新的替代品,但我只是想知道这一点。 - 什么是更新的替代品?
-
就我个人而言,我在实际符合要求的单一场合使用了
promise.then(resolveHandler, rejectHandler).catch(catchHandler)“模式”。然后我意识到需要重新访问并不再使用该模式 -
我很确定这里有几个重复的,因为这肯定已经被问过了。我会尽力找到他们。主要区别在于
.catch()处理程序还将捕获resolveHandler中的任何异常或拒绝,但rejectHandler不会。
标签: javascript node.js promise