对于异步函数, 简单的try-catch并不能直接捕捉到。
比如说
function func1 () {
try {
func2()
} catch (error) {
}
}
function func2() {
setTimeout(function () {
throw new Error("error")
}, 1000)
}
这里就无法catch到func2里面throw的error
所以应该是func2返回一个封装在Promise里面的函数,在func1里面用await来接收。因为await是对一个表达式求值。如果await后面是promise的话,就会等待Promise返回才执行。
Comments
Post a Comment