被捕获(诺言)...使用捕获
为什么以下代码报告被捕获的
错误时,被拒绝的错误?
function Test() {
this.start = function(action) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (action == "fail") return reject("rejected");
resolve("resolved");
}, 1000);
});
}
}
const test = new Test();
const promise = test.start("fail");
promise.then(console.log);
promise.catch(console.error);
输出(在浏览器中)为:
catch()
uck> und offerf(承诺)被拒绝的从呼叫拒绝的
Why does the following code report an Uncaught (in promise) rejected
error when it is being caught?
function Test() {
this.start = function(action) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (action == "fail") return reject("rejected");
resolve("resolved");
}, 1000);
});
}
}
const test = new Test();
const promise = test.start("fail");
promise.then(console.log);
promise.catch(console.error);
The output (in a browser) is:
rejected
from the catch()
Uncaught (in promise) rejected
from the call to reject
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您分叉您的承诺链:
拒绝是被
.catch
抓住的,但是它也可以通过。然后
分支。这两个分支都独立解决。而且,您不会在上捕获拒绝。然后,然后导致拒绝错误。
比较:
这里的链条看起来像这样:
拒绝将 skip
。然后
处理程序,然后转到最近的.catch
。You're forking your promise chain:
The rejection is being caught by the
.catch
just fine, but it also goes through the.then
branch. Both of those branches are resolved independently. And you're not catching the rejection on the.then
branch, leading to the uncaught rejection error.Compare with:
Here the chain looks like this:
The rejection will skip the
.then
handler and go to the nearest.catch
.好的。答案很明显,但很容易错过。
。然后(...)
返回另一个承诺。因此,您必须将.catch(...)
附加到其中。解决方案:
或更明确:
@deceze
的答案/解释非常好。Ok. The answer is obvious, yet easy to miss.
.then(...)
returns another promise. So you have to attach the.catch(...)
to THAT.Solution:
OR more explicitly:
@deceze
's answer/explaination is pretty good.这是校正的代码:
您需要链链
。
Here is the corrected code :
you need to chain .then() and .catch() for it to work,
because .then() will return a new promise, and it's that promise that will throw the error you need to catch
没有任何承诺
因为您
。
将您的拒绝转化为解决您的承诺,
希望这会有所帮助
Because there's no promise made for your .then
Either you change your function call into
or
change your reject into resolve on your promise
hope this helps
您的代码说以下内容:
您创建承诺并给出字符串参数(“失败”)。
您会抓住承诺,并显示
出带有字符串参数“拒绝”的拒绝函数的错误。
希望它有帮助。
Your code says the following:
You create a promise and give a string parameter ("fail").
You catch the promise and show the error
You return the reject function with the string parameter "rejected".
Hope it help.