当前位置: 首页 > Web前端 > JavaScript

[JS]无极拒捕研究

时间:2023-03-27 16:20:47 JavaScript

同步更新到你自己的语雀,格式更易看。可以搬家:https://www.yuque.com/diracke...目标:1.看try...catch...和.then().catch()catch的区别。2、throwerr是否可以被promise中的两个catch捕获。第一篇文章中使用的代码会有handle1、handle2、handle3、handle4分别对应四种不同的情况。运行结果和结论写在每行代码之后。先写结论:1..then.catch中的catch优先级高于try...catch...中的catch;2.throwinpromise会将promise实例变为rejected状态;3、异步情况下,try...catch...中的catch不能处理rejected状态promise.asyncfunctionaxiosLike(isSuccess,info={}){returnnewPromise((resolve,reject)=>{if(isSuccess){if(info.code==="0"){resolve(info.data);}else{reject(info.msg);}}else{throw"serveerr";}});}consttempInfoSuccess={code:"0",data:{name:"mike",age:15},msg:"success",};consttempInfoFailed={code:"2",data:{name:"mike",age:15},msg:"unknowexception",};asyncfunctionhandle1(isSuccess,info={}){尝试{constres=awaitaxiosLike(isSuccess,info);console.log("res->",res);}catch(err){console.log("err->",err);}}//handle1(true,tempInfoSuccess);//res->{name:"mike",age:15}//handle1(true,tempInfoFailed);//err->未知异常//handle1(false);//err->serveerr//try...catch的catch会捕获reject()的状态,可以得到reject(ererr//try...catchinr)也会捕获throw抛出的异常并得到errfunctionhandle2(isSuccess,info={}){axiosLike(isSuccess,info).then((res)=>{console.log("res->",res);}).catch((err)=>{console.log("err->",err);});}//handle2(true,tempInfoSuccess);//res->{name:"mike",age:15}//handle2(true,tempInfoFailed);//err->未知异常//handle2(false);//err->serveerr//Promise.then()中的catch.catch()会捕获到reject()的状态,可以得到reject(err)中的err//Promise.then()中的catch.catch()也会捕获throw抛出的异常,也会得到throwerr3(isSuccess,info={})的errfunction句柄{try{axiosLike(isSuccess,info).then((res)=>{console.log("res->",res);}).catch((err)=>{console.log("errin.then.catch->",err);});}catch(err){console.log("try...catch->",err);}}//handle3(true,tempInfoFailed);//errin.then.catch->未知异常//handle3(false);//在.then中出错。赶上->服务错误//functionhandle4(isSuccess,info={}){尝试{axiosLike(isSuccess,info).then((res)=>{console.log("res->",res);});}catch(err){console.log("try...catch->",err);}}//handle4(true,tempInfoFailed);//报错如下↓/*UnhandledPromiseRejectionWarning:unknownexceptionUnhandledPromiseRejectionWarning:UnhandledPromiseRejection。这个错误要么是在没有catch块的情况下在异步函数内部抛出,要么是因为拒绝了一个没有用.catch()处理的承诺。*///try...catch的catch无法处理拒绝状态promise.handle4(false);//报错如下↓/*UnhandledPromiseRejectionWarning:serveerrUnhandledPromiseRejectionWarning:UnhandledPromiseRejectionWarning:UnhandledPromiseRejection。这个错误要么是在没有catch块的情况下在异步函数内部抛出,要么是因为拒绝了一个没有用.catch()处理的承诺。*///throwerr也把promise实例变成了rejected状态,try...catch的catch无法处理//观察handle4()的两次执行结果,可以发现异步结果中的error,尝试...c无法处理的问题