[英]How can calling a catch() method "try catch" the exception of a promise?
换句话说,我们通常不能简单地通过调用另一个方法来“尝试捕获”异常。
但是我们可以通过以下方式处理 promise 的异常
promise
.then()
.catch();
或者
promise
.then(fulfillmentHandler, rejectionHandler);
如果第一种情况下的promise.then()
抛出异常,那么如何在该 promise 上调用catch()
方法来处理之前发生的异常?
我们通常必须通过使用包装它来处理异常
try {
// doSomething
} catch (err) {
// handle the error
}
因此,如果then()
返回的 promise 发生异常, then()
在promise.then()
运行时代码是否必须处理异常? 简单地调用对象上的方法通常无法处理其异常(在这种情况下,在then()
返回的承诺上调用catch()
),因为没有这样的包装?
你能做的最好的事情就是查找一些 promise polyfill。
任何传递给promise 的函数,在构造函数中或在.then
有一个回调在内部包装在try-catch 中,如果此函数抛出,它将触发下一个.catch
(或抛出未处理的promise 拒绝错误)。
然而,在 try-catch 中包装 promise 不会捕获未处理的拒绝,因为它们有些特殊。 要抓住它们,您必须使用它:( 参考)
window.addEventListener('unhandledrejection', function(event) {
console.error(`Unhandled rejection (promise: ${event.promise}, reason: ${event.reason}).`);
});
如果
then()
返回的 promise 发生异常,then()
在promise.then()
运行时代码是否必须处理异常?
then
返回的 Promise 中发生的异常还没有发生,它只会发生在那个 Promise 的微任务中,在主任务完成后。
Promise.resolve() .then( callback ) // still synchronously in the main task, no error yet .catch( console.error ); console.log( "done with main task" ); // this will only get executed in a micro-task, when the main task is done function callback() { console.log( "will now throw" ); throw new Error( "not good" ); }
因此这些.catch()
.then()
和.catch()
返回的 Promise 对象将能够很好地附加回调,并且主任务中的任何内容都不会抛出。
唯一可能令人困惑的是 Promise 构造函数,它将同步包装异常:
const promise = new Promise( () => { console.log( "will now throw" ); throw new Error( "not good" ); } ); console.log( "yet here we are fine" );
但这与 Events 并没有什么不同:
addEventListener( 'test', e => { console.log( "will now throw" ); throw new Error( "not good" ); } ); dispatchEvent( new Event( "test" ) ); console.log( "Yet we are fine" );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.