异步编程: async / await 如果右边方法执行出错怎么办
Opened this issue · 0 comments
leslie1943 commented
async / await 如果右边方法执行出错怎么办
- 1 使用
Promise.catch
捕获
console.info(1)
async function f() {
await new Promise(function (resolve, reject) {
console.info(2)
throw new Error('出错了')
}).catch(err => { // 这里的异常捕获不会执行后续代码的执行
console.info(3)
console.info('执行失败了.')
})
console.info(4)
}
f()
// 输出结果 1,2,3,执行失败了,4
- 2 使用
try-catch
async function f() {
try {
// 使用 try-catch的时候,会把容易引发的异常的代码写道 try里
await new Promise(function (resolve, reject) {
throw new Error('出错了')
})
console.info('这里不会执行了')
} catch (err) {
console.info('异常了')
}
}