结论
- promise 用错误回调和.catch()来处理错误
- async用.catch()和try{}catch(){}来捕捉错误
可能是从jQuery用过来的,个人更喜欢promise的写法
痛点er
到了新公司出奇的忙,忙着熟悉文化、制度、框架、业务。业务中对异步的封装和使用混合了promise和async,要把这两种写法关系理清。
promise工厂
function pr(flag = true) { return new Promise((res, rej) => { setTimeout(() => { flag ? res("success") : rej("error") }, 2000) }) }
promise 的错误捕捉
错误回调处理reject(),.catch()处理抛出的异常和reject(),
function catch1() {
pr(false).then(() => {
// error函数捕捉不到这个错误
throw 'catch1 error'
}, (e) => {
// 只能处理promise的reject()错误
console.log('catch1 reject', e)
})
}
function catch2() {
pr().then(() => {
// catch函数可以捕捉到这个错误
throw 'catch2 error'
}).catch((e) => {
// 处理reject() ,
//处理成功回调和错误回调throw出的错误
console.log('catch2', e)
}).finally(() => {
console.log('catch2 , finally')
})
}
catch1()
catch2()
async函数的错误捕捉
async function catch3() {
try {
const res = await pr(false).catch((e) => {
// 可以省略让下面的catch捕捉
// reject会被捕捉
console.log(3, 'catch()', e)
throw e
})
console.log('catch3', res)
throw "error test"
return res
} catch (e) {
console.log('catch3 try catch', e)
throw e
}
}
catch3()
promise和async的相互转换和错误捕捉
async是promise的语法糖
async function asy(){ return await 1 }
asy() instanceof Promise // true
async function catch3() {
// promise转await
try {
const res = await pr()
console.log(3, 'catch3', res)
throw "catch3 throw error"
return res
} catch (e) {
console.log(3, 'try catch', e)
// 捕捉上面的throw
// 如果上面没有异常回调,异常回调会在这捕捉,再抛出也会被后面的异常回调捕捉到
throw e
}
}
async function catch4() {
// try catch 和.catch()二选一
// 捕捉catch3错误回调抛出的异常
// 捕捉catch3的throw
try {
await catch3().catch((e) => {
console.log(4, 'catch()', e)
})
} catch (e) {
console.log(4, 'try catch', e)
}
};
function catch5() {
// async 转promise
// 错误回调 和.catch()二选一
catch3().then(() => {
}, (e) => {
console.log(5, 'reject()', e)
}).catch((e) => {
console.log(5, 'catch()', e)
})
}
async function catch6() {
const res = await pr().then((d) => {
return d
}, (e) => {
return e
}).catch((e) => {
console.log(6, 'catch()', e)
return e
});
//await返回的参数就是promise的return
// 如果都能把错误return出来,可以不用捕捉错误
console.log(6, res) // d e e
}
catch4()
catch5()
catch6()
如果感觉对小伙伴有帮助请点赞!
如果感觉对小伙伴有帮助请点赞!
有错误的地方欢迎小伙伴指正!!
有错误的地方欢迎小伙伴指正!!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。