async/await可以理解为promise的语法糖

相较于promise

async/await在书写过程中简化了除功能代码以外的api

使得代码语义更加清晰明了

那么重点来了

promise通过catch回调来处理错误

那么async/await如何处理错误呢

方法一:try...catch

const getStudent = async () =>{
    try {
      const inf = await axios.get('http://localhost:3000/api1/students')
      console.log('inf',inf.data);
    } catch (error) {
      console.log('error',error);
    }
  }

这是较为常见的用法,但还是稍稍显的没那么优雅

方法二:使用await-to-js库

首先需要安装await-to-js库

yarn add await-to-js

接着引入

import to from 'await-to-js'

最后就是使用了

  const getStudent = async () =>{
      const [err,inf] = await to(axios.get('http://localhost:3000/api1/students'))

      if(err){
        console.log('err',err);
        return
      }
      console.log('inf',inf);
  }

简单解释一下,to方法可传入一个promise对象,并且返回值是一个数组,数组的第一个元素用于接受rejected后返回的参数,第二个元素用于接收resolved后返回的参数,若数组的第一个元素不为空,则表明被rejected,综上,便可优雅的处理async/await的异常了。

Logo

鸿蒙生态一站式服务平台。

更多推荐