异步加载async await

关于async

在函数前面加上async关键字,表示函数是异步的

 async function timeout() {
     return 'hello world!'
 }

关于await

在Vue中,我们通常会使用axios来调用接口获取数据。我们可以将axios封装成一个异步函数,然后在Vue组件中使用async/await来获取数据。 优势在于处理 then 链,使代码看起来像同步代码一样

常用的写法

async fetchPersonalVeri(params) {
   const result = await operatorApi.operatorPersonalVeri(params);
    this.personalVeriInfo = result || {};
},

实例

// 转正
    async transferFun(){
      try {
        // 定义异步加载 发起GET请求获取数据
         const res = await crudBizIntendedStudent.transfer(this.paymentForm) 
        // const res="1765668290854170626&202403071718200971765668290854170626"
         if(res){
           let arr=res.split("&")
           this.pdfHref=this.baseApi+'/file/文档/'+arr[1]+'.pdf'
           this.pdfId=arr[0]
           this.crud.refresh()
           this.studentPaymentVisible=false
           this.crud.cancelCU()
           this.zhuanzhengVisible=true
         }

       } catch (err) {
         this.crud.notify(err.data.message)// 打印错误信息
       }
    },
    // 复制签名地址
   async buildSignUrlPDF(pdfId){
      let baseUrl=window.location.origin
      console.log(baseUrl)
      // type: 1未签名2已签名 pay: 1交费2退费
      let resUrl=baseUrl+'/viewAgreement?id='+pdfId+'&type=1&pay=1'
      clipboard(resUrl, event)
    },

await 报错

在使用async await 时抛出异常 Unexpected reserved word ‘await‘ 代码如下:

原代码

async studentPaymentFun(){
   this.$refs['paymentForm'].validate((valid) => {
    if (valid) {
       try {
          const res =  await crudPayment.add(this.paymentForm) // 发起GET请求获取数据
          if(res){
            let arr=res.split("&")
            this.pdfHref=this.baseApi+'/file/文档/'+arr[1]+'.pdf'
           ....
          }
        } catch (err) {
          this.crud.notify(err.data.message)// 打印错误信息
        }
     }
   })
},

后经过排查发现错把async加在了外部函数上修改为一下代码运行正常

studentPaymentFun(){
   this.$refs['paymentForm'].validate(async (valid) => {
    if (valid) {
       try {
          const res =  await crudPayment.add(this.paymentForm) // 发起GET请求获取数据
          if(res){
            let arr=res.split("&")
            this.pdfHref=this.baseApi+'/file/文档/'+arr[1]+'.pdf'
           ....
          }
        } catch (err) {
          this.crud.notify(err.data.message)// 打印错误信息
        }
     }
   })
},
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值