VUE:使用async和await实现axios同步请求

🖥️ NodeJS专栏:Node.js从入门到精通
🖥️ 博主的前端之路:前端之行,任重道远(来自大三学长的万字自述)
🧧 加入社区领红包:海底烧烤店ai(从前端到全栈)
🧑‍💼个人简介:即将大三的学生,一个不甘平庸的平凡人🍬
👉 你的一键三连是我更新的最大动力❤️!

🏆分享博主自用牛客网🏆:一个非常全面的面试刷题求职网站,真的超级好用(点击跳转)🍬

一、axios异步请求出现的问题

handleClick(tab, e) {
      this.$axios({
        url: '/operatingsystem/student/selectStudentsByClno',
        method: 'get',
        params: {
          clno: tab.props.name
        }
      }).then(res => {
        this.StudentsByClno = res.obj
      })
    },

在页面中调用methods中handleClick函数中的axios请求时,因为.then的特性,可能会出现后端返回的值还没赋值到StudentsByClno中时页面就对StudentsByClno中的数据进行渲染,从而导致报错或者后端数据来不及渲染到页面之上

二、解决办法:使用async 和await

async 和await 介绍

在ES7标准中新增了asyncawait关键字,作为处理异步请求的一种解决方案,实际上是一个语法糖,在ES6中已经可以用生成器语法完成同样的操作,但是async/await的出现使得用这样的方式处理异步请求更加简单和明白。

使用asyncawait 将会使axios从异步请求变为同步请求。

异步函数也就是意味着这个函数的执行不会阻塞后面代码的执行。

注意事项

  1. 只有在async方法里面才能使用await操作符;
  2. await操作符是针对Task对象的;
  3. 当方法A调用方法B,方法B方法体内又通过await调用方法C时,如果方法C内部有异步操作,则方法B会等待异步操作执行完,才往下执行;但方法A可以继续往下执行,不用再等待B方法执行完。
    async handleClick(tab, e) {
      await this.$axios({
        url: '/operatingsystem/student/selectStudentsByClno',
        method: 'get',
        params: {
          clno: tab.props.name
        }
      }).then(res => {
        this.StudentsByClno = res.obj
      })
    },

三、突发问题

在使用async/await时报了如下错误:

 ERROR  Failed to compile with 1 error                                                                                                                         下午8:13:38

This dependency was not found:

* regenerator-runtime/runtime.js in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!.
/node_modules/vue-loader-v16/dist??ref--0-1!./src/views/Challenge.vue?vue&type=script&lang=js

To install it, you can run: npm install --save regenerator-runtime/runtime.js

让我运行:

npm install --save regenerator-runtime/runtime.js

可运行后又报错:

info: please complete authentication in your browser...Completed in 0ms
npm ERR! code 128
npm ERR! command failed
npm ERR! command git ls-remote ssh://git@github.com/regenerator-runtime/runtime.js.git
npm ERR! git@github.com: Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ailjx\AppData\Local\npm-cache\_logs\2021-11-11T12_30_04_836Z-debug.log

还出现过运行上述指令后弹出一个github的框要求输入一个什么东西(我忘记了)

四、解决办法

直接装完整包

npm install regenerator-runtime

👉👉 基础不牢,地动山摇! 快来和博主一起来牛客网刷题巩固基础知识吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Baker-Chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值