当前位置: 首页 > 科技观察

你可以使用Async-Await,但是你知道如何处理错误吗?

时间:2023-03-13 23:08:13 科技观察

前言大家好。我是林三鑫。用最通俗易懂的话讲最难的知识点是我的座右铭,那么当你使用这个请求函数时,它看起来像这样://封装请求函数constrequest=(url,params)=>{returnnewPromise((resolve,reject)=>{//...dosomething})}//consthandleLogin=()=>{request('/basic/login',{usename:'sunshine',password:'123456'}).then(res=>{//successdosomething}).catch(err=>{//faildosomething})}可以看到,当你的请求成功时,then方法会被调用,当你的请求失败时,会调用catch方法。async/awaitPromise的出现解决了很多问题,但是如果请求和顺序要求很多,难免会出现嵌套问题,可读性差,例如:consthandleLogin=()=>{request('/basic/login',{usename:'sunshine',password:'123456'}).then(res=>{//登录成功后获取用户信息request('/basic/getuserinfo',res.id).then(info=>{this.userInfo=info}).catch()}).catch(err=>{//faildosomething})所以这个时候async/await出现了,它的作用是:以同步的方式执行异步操作,如果上面的代码使用了async/await,可以改写为:consthandleLogin=async()=>{constres=awaitrequest('/basic/login',{usename:'sunshine',password:'123456'})constinfo=awaitrequest('/basic/getuserinfo',{id:res.id})this.userInfo=info}这样代码的可读性比较高,不会出现刚才的嵌套问题,但现在还有另一个公关问题。Promise有catcherror回调来保证请求出错后如何处理,但是async/await是如何捕获错误的呢?async-to-js其实已经有一个库async-to-js已经帮我们做了这件事,我们可以看看它是怎么做到的。它的源代码只有十几行。我们应该阅读它的源代码并学习它的思想。源码很简单/***@param{Promise}传入的请求函数*@param{Object=}errorExt-扩展错误对象*@return{Promise}返回一个Promise*/exportfunctionto(promise,errorExt){returnpromise.then(data=>[null,data]).catch(err=>{if(errorExt){constparsedError=Object.assign({},err,errorExt)return[parsedError,undefined]}return[err,undefined]})}exportdefaulttosourcecodesummary:tofunctionreturnsaPromiseandvalueisanarray,array中有两个元素,如果元素有索引0不是空值,表示请求报错。如果索引0处的元素为空值,则说明请求没有报错,即使用成功,非常简单。我们应该如何使用它来发挥作用?其实很简单,还是刚才的例子consthandleLogin=async()=>{const[resErr,res]=awaitto(request('/basic/login',{username:'sunshine',password:'123456'}))if(resErr){//失败返回}const[userErr,info]=awaitto(request('/basic/getuserinfo',{id:res.id}))if(userErr){//faildosomthingreturn}this.userInfo=info}这么说吧,偶尔看看一些库的源码,还是可以学到东西的!!!