问题描述
关于在 setTimeout 中 try-catch for 函数的简单问题
Simple question about try-catch for function in setTimeout
try {
setTimeout(function () {
throw new Error('error!');
}, 300)
} catch (e) {
console.log('eeee!')
console.log(e)
}
为什么不使用 catch-block?
Why dont work catch-block?
关于这个我能读到什么?
What I can read about this?
P.S:关于处理此类错误的可能性的问题.不要回答关于承诺的问题
P.S: Question about possibility of handling errors like this. Dont answer about promises
推荐答案
计划使用 setTimeout
运行的函数在主循环中执行,在产生它们的代码体之外.
Functions scheduled to run with setTimeout
are executed in the main loop, outside the body of code that originated them.
要处理错误,请将 try-catch
放在 setTimeout
处理程序中:
To handle errors, put the try-catch
inside the setTimeout
handler:
setTimeout(function () {
try {
throw new Error('error!');
} catch (e) {
console.error(e);
}
}, 300)
如果您需要从名为 setTimeout
的块访问 Error
对象,请使用 Promises:
If you need to access the Error
object from block that called setTimeout
, use Promises:
const promise = new Promise((resolve, reject) => {
setTimeout(function () {
try {
throw new Error('error!');
resolve(); // if the previous line didn't always throw
} catch (e) {
reject(e)
}
}, 300)
})
promise
.then(result => console.log("Ok " + result))
.catch(error => console.error("Ouch " + error))
上面的这个例子并不是用 Promise
处理这种情况的最优雅的方式.相反,实现一个 delay(ms)
函数,如下所示:
This example above is not the most elegant way of handling the case with a Promise
. Instead, implement a delay(ms)
function like this:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
然后调用
delay(300).then(myFunction).catch(handleError)
这篇关于处理来自 setTimeout 的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!