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

 

posted on   独自去流浪  阅读(282)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示