在异步回调函数生成的错误上使用 try catch
using try catch on error generated by asynchronous callback function
我正在尝试捕获由异步 javascript 回调函数引起的错误,
try{
setTimeout(()=>{
throw err
console.log("after throw")
}, 1000)
}catch(e){
console.log("caught");
}
但是你们中的许多人可能都知道 catch 块永远不会执行,所以 这里到底发生了什么?
我知道我可以使用 promises 和 async/await,
实现类似的事情
async foo(){
try{
await setTimeoutPromise(1000);
}catch(e){
alert("caught");
}
}
当您使用 setTimeout 时,回调被推入事件循环(移出 JS 引擎并进入 runtime/browser 领域)并且您的 foo
函数立即退出。
超时后且堆栈为空后,事件循环会将回调放入堆栈并运行。这就是 try/catch 和回调相互独立的原因。这也是为什么 setTimeout(1000)
并不意味着 秒后 而是 不早于并且稍微接近一秒 .
见What the heck is the event loop anyway? | Philip Roberts | JSConf EU
这是两个不同的东西。
第一个代码不会捕获错误,因为它是异步发生的,try...catch
只会捕获同步抛出的异常。
第二个代码 将 捕获错误,因为 await
'synchronize' 代码(使其看起来和工作起来就像同步的一样) , 以及错误 thrown only by await
: if you haven't been used it, you would get only a rejected promise (You can't really throw anything from an async function!)
要使第一个代码正常工作,请在回调中移动 try...catch
:
setTimeout(()=>{
try{
throw err
}catch(e){
console.log('catched')
}
console.log("after throw")
}, 1000)
我正在尝试捕获由异步 javascript 回调函数引起的错误,
try{
setTimeout(()=>{
throw err
console.log("after throw")
}, 1000)
}catch(e){
console.log("caught");
}
但是你们中的许多人可能都知道 catch 块永远不会执行,所以 这里到底发生了什么?
我知道我可以使用 promises 和 async/await,
实现类似的事情async foo(){
try{
await setTimeoutPromise(1000);
}catch(e){
alert("caught");
}
}
当您使用 setTimeout 时,回调被推入事件循环(移出 JS 引擎并进入 runtime/browser 领域)并且您的 foo
函数立即退出。
超时后且堆栈为空后,事件循环会将回调放入堆栈并运行。这就是 try/catch 和回调相互独立的原因。这也是为什么 setTimeout(1000)
并不意味着 秒后 而是 不早于并且稍微接近一秒 .
见What the heck is the event loop anyway? | Philip Roberts | JSConf EU
这是两个不同的东西。
第一个代码不会捕获错误,因为它是异步发生的,try...catch
只会捕获同步抛出的异常。
第二个代码 将 捕获错误,因为 await
'synchronize' 代码(使其看起来和工作起来就像同步的一样) , 以及错误 thrown only by await
: if you haven't been used it, you would get only a rejected promise (You can't really throw anything from an async function!)
要使第一个代码正常工作,请在回调中移动 try...catch
:
setTimeout(()=>{
try{
throw err
}catch(e){
console.log('catched')
}
console.log("after throw")
}, 1000)