关于setTimeout中函数的try-catch的简单问题
try {
setTimeout(function () {
throw new Error('error!');
}, 300)
} catch (e) {
console.log('eeee!')
console.log(e)
}
为什么不工作catch-block?
我能读到什么?
P.S:关于处理这样的错误的可能性的问题。不要回答承诺
计划与setTimeout
一起运行的函数在主循环中执行,在发起它们的代码体外部。
要处理错误,请将try-catch
放在setTimeout
处理程序中:
setTimeout(function () {
try {
throw new Error('error!');
} catch (e) {
console.error(e);
}
}, 300)
如果您需要从名为Error
的块访问setTimeout
对象,请使用Promises:
const promise = new Promise((resolve, reject) => {
setTimeout(function () {
try {
throw new Error('error!');
} catch (e) {
reject(e)
}
}, 300)
})
promise
.then(result => console.log("Ok " + result))
.catch(error => console.error("Ouch " + error))
上面这个例子并不是使用Promise
处理案例的最优雅方式。相反,实现这样的delay(ms)
函数:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
然后打电话
delay(300).then(myFunction).catch(handleError)
你可以在这个Node.js官方doc找到很好的解释。
问题是当你的setTimeout()
函数的回调执行时,try { } catch(err) { }
块已经退出。另请注意,回调可能会导致Node.js进程崩溃。
但是,如果你想处理setTimeout()
函数回调中的错误,那么你可以使用process
全局EventEmitter对象来监听它们。
process.on('uncaughtException', function(err){
console.log(err)
})
因为catch块在词法上围绕setTimeout
调用,但这不是抛出的函数。直接翻译,是
setTimeout(function () {
try {
throw new Error('error!');
} catch (e) {
console.log('eeee!');
console.log(e);
}
}, 300);