async和await在项目中的应用

Async基础知识:

  • async函数是ES7标准引入的语法,基于Generator函数实现的,也就是说是Generator函数的语法糖。什么是Generator函数?(留个坑)
  • 返回值是Promise,可以使用then方法来指定下一步操作
  • 使用asyn关键字表明函数是一个async函数,内部使用await关键字表明需要等待异步任务结束后才继续往下执行
  • 参考资料:http://es6.ruanyifeng.com/#docs/async

为了实践async和await,我把现在在做的vue电商项目中的异步请求函数都换成了async和await方式。

1.分类页,获取分类数据

原来的代码:

vue created

created() {
  this.$ajax.get('http://localhost:3000/category/').then((res) => {
    const data = res.data // 成功拿到数据
   // 操作省略 }).
catch(function (error) { console.log(error) }) },

效果图:

现在,改成async和await

首先,在vue methods里定义一个async方法

methods: {
  async getCategory() {
    let res = await this.$ajax.get('http://localhost:3000/category/')
    if (res.status === 200) {
      return res.data // 成功拿到数据
    }
  },
}

然后呢,在vue created里调用

created() {
  this.getCategory().then(res => {
    const data = res // 成功拿到数据
  // 操作省略 })
.catch(function (error) {
    console.log(error)
  })
},

这样把代码流程改成了同步形式。测试了下,效果一样。

2.商品列表页,获取商品数据

效果图:

原来的代码,vue created:

created() {
  this.cat_id = this.$route.query.catId
  this.$ajax.get('http://localhost:3000/items', {
    params: {
      catId: this.cat_id
    }
  }).then((res) => {
    console.log(res.data)
  }).catch((error) => {
    console.log(error)
  })
},

改用async:

vue methods里:

methods: {
  async getItems(catId) {
    let res = await this.$ajax.get('http://localhost:3000/items', {
      params: {
        catId: catId
      }
    })
    if (res.status === 200) {
      return res.data
    }
  },
}

vue created:

created() {
  this.cat_id = this.$route.query.catId
  this.getItems(this.cat_id).then(res => {
    this.goodsData = res
  }).catch(function (error) {
    console.log(error)
  })
},

完成,效果一致。

我写技术博客的目的主要是整理自己做过的功能,主要是写给自己看,当然,我尽量写清楚。

若给你造成误解,我很抱歉。若给你带来帮助, 我很欣慰。

有疑问欢迎交流 扣扣:2136946914

原文地址:https://www.cnblogs.com/cathy1024/p/10281247.html