【发布时间】:2017-08-02 23:05:22
【问题描述】:
是否可以使用 ES6 .catch 的 Promise 语法来捕获异步错误?例如,以下内容不起作用(.catch 无法捕获错误):
new Promise((resolve, reject)=>{
setTimeout(()=>{throw new Error("uh oh")}, 1);
}).then(number=>{
console.log("Number: " + number);
}).catch(e=>{
console.log("Error: " + e);
});
但是这个同步版本可以:
new Promise((resolve, reject)=>{
throw new Error("uh oh");
}).then(number=>{
console.log("Number: " + number);
}).catch(e=>{
console.log("Error: " + e);
});
使用 try/catch 块并 rejecting 捕获错误是唯一的解决方案吗?
new Promise((resolve, reject)=>{
try {
setTimeout(()=>{throw new Error("uh oh")}, 1);
}
catch(e) {
reject(e);
}
}).then(number=>{
console.log("Number: " + number);
}).catch(e=>{
console.log("Error: " + e);
});
为了这个问题,假设抛出错误的代码部分在另一个命名函数中,因此它无权访问reject 函数。
谢谢!!
编辑:Here is a more complete example of what I'd like to do, in JSFiddle.
【问题讨论】:
-
assume the part of the code that is throwing the Error is in another named function- 这个(在你的代码中不存在)函数是否返回一个 Promise? -
是的,另一个函数正常返回一个promise,但是因为那个函数内部的一个异步函数抛出了一个错误,整个函数都抛出了一个错误。而且我知道第一个 sn-p 不能仅仅通过运行它来工作。期望的行为是“错误:”应该是 console.log'ed,但实际上错误是从链式调用中传播出来的:i.imgur.com/J6CyFW9.png
-
不,
catch不会捕获超时内引发的错误,因为它位于不同的“线程”中。 -
我想我似乎应该放弃对错误
throw的渴望并拒绝它...? -
这可能是有用的阅读:stackoverflow.com/questions/33445415/…
标签: javascript asynchronous ecmascript-6 promise