Promise 中的错误处理
promise 抛出的错误可以被 promise 链最后的 catch 方法捕捉到
function fetch(callback) {
return new Promise((resolve, reject) => {
throw Error('用户不存在')
})
}
fetch().then(result => {
console.log('请求处理', result) // 永远不会执行
}).catch(error => {
console.log('请求处理异常', error) // 请求处理异常 用户不存在
})
但是,在 promise 中使用 macroTask 抛出的错误不能被 promise 链中的 catch 捕捉
function fetch(callback) {
return new Promise((resolve, reject) => {
setTimeout(() => {
throw Error('用户不存在')
// 正确的做法应该是: reject('...')
})
})
}
fetch().then(result => {
console.log('请求处理', result) // 永远不会执行
}).catch(error => {
console.log('请求处理异常', error) // 永远不会执行
})
async/await 中的错误处理
await 是 generator 或者 then 的语法糖,所以在 await 后面的语句,相当于 promise 的 then 代码块中的内容,所以,await 等待的异步函数 reject 掉时,await 之后的代码不会执行:
function fetch(callback) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject()
})
})
}
async function main() {
const result = await fetch()
console.log('请求处理', result) // 永远不会执行
}
main()
正确的做法应该是使用 try catch 捕捉:
function fetch(callback) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('no')
})
})
}
async function main() {
try {
const result = await fetch()
console.log('请求处理', result) // 永远不会执行
} catch (error) {
console.log('异常', error) // 异常 no
}
}
main()
不过,和 promise 一样,async 同样不能处理异步函数内 throw 出的 error,也应该使用 reject。总结来说,就是异步过程内部不要 throw error,而要 reject error.