关于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)// 打印错误信息
}
}
})
},