结论Promise使用错误回调和.catch()来处理错误async使用.catch()和try{}catch(){}来捕获错误可能是从jQuery开始使用的,就个人而言,我更喜欢承诺的措辞。痛点er在新公司出奇的忙,忙着熟悉文化、制度、框架、业务。业务中对异步的封装和使用混用了promise和async,必须搞清楚这两种写法的关系。promise工厂函数pr(flag=true){returnnewPromise((res,rej)=>{setTimeout(()=>{flag?res("success"):rej("error")},2000)})}Promise的错误捕获错误回调处理reject(),.catch()处理抛出的异常和reject(),functioncatch1(){pr(false).then(()=>{//错误函数无法捕获Thiserrorthrow'catch1error'},(e)=>{//只能处理promise的reject()错误console.log('catch1reject',e)})}functioncatch2(){pr().then(()=>{//catch函数可以捕获这个错误throw'catch2error'}).catch((e)=>{//handlereject(),//处理成功回调和错误回调throwerrorconsole.log('catch2',e)}).finally(()=>{console.log('catch2,finally')})}catch1()catch2()asyncfunctionerrorcatchasyncfunctioncatch3(){try{constres=awaitpr(false).catch((e)=>{//可以省略,让下面的catchcatch//reject会被捕获console.log(3,'catch()',e)throwe})console.log('catch3',res)throw"errortest"returnres}catch(e){console.log('catch3trycatch',e)throwe}}catch3()promise和async之间的互换和错误捕获async是promiseasyncfunctionasy(){returnawait1}asy()instanceofPromise//trueasyncfunctioncatch3(){//promisetoawaittry{constres=awaitpr()console.log(3,'catch3',res)throw"catch3throwerror"returnres}catch(e){console.log(3,'trycatch',e)//catch上面的Throw//如果上面没有异常回调,这里会捕获异常回调,如果抛出,会被下面的异常回调捕获throwe}}asyncfunctioncatch4(){//trycatchand.catch()两种选择1//捕获catch3错误回调抛出的异常//捕获catch3的throwtry{awaitcatch3().catch((e)=>{console.log(4,'catch()',e)})}catch(e){console.log(4,'trycatch',e)}};functioncatch5(){//异步承诺//选择错误回调和.catch()catch3().then(()=>{},(e)=>{console.log(5,'reject()',e)}).catch((e)=>{console.log(5,'catch()',e)})}asyncfunctioncatch6(){constres=awaitpr().then((d)=>{returnd},(e)=>{returne}).catch((e)=>{缺点ole.log(6,'catch()',e)返回e});//await返回的参数是promise的返回//如果可以返回错误,则不需要捕获错误console.log(6,res)//dee}catch4()catch5()catch6()如果觉得对朋友有帮助,请点个赞吧!如果觉得对朋友有帮助,请点个赞吧!有错误欢迎朋友指正!!有错误欢迎朋友指正!!
