async/await是非常好用的一个语法,需结合promise来使用。
比如有两个串行接口,第一个是获取authCode,第二个是获取accessToken,这个在微信中比较常见:
axios({ url:'/api/authCode',method:'get' });
axios({ url:'/api/accessToken',method:'get' });
要获取accessToken,则必先获取authCode,这样就形成了等待关系。
我们知道async和await是生成器的语法糖,生成器是函数的中断机制,我们要知道什么时候中断、中断后从哪里继续执行,因此我们可以将接口包装成promise。
import axios from 'axios'
export default {
name: "test2",
methods:{
getAuthCode(){//需包装成promise
return new Promise((resolve,reject)=>{
axios({url:'/api/authCode',method:'get'}).then(res=>{
resolve(res) //中断返回
}).catch(err=>{
reject(err)
})
})
},
getAccessToken(){//需包装成promise
return new Promise((resolve,reject)=>{
axios({url:'/api/accessToken',method:'get'}).then(res=>{
resolve(res) //中断返回
}).catch(err=>{
reject(err)
})
})
},
async getList(){//获取用户列表信息
let res1 = await this.getAuthCode()
let res2 = await this.getAccessToken(res1.data.authCode)
let token = res2.data.accessToken
if(token) {
axios({url:`/api/getUserList?accessToken=${token}`,method:'get'}).then((res)=>{
console.log(res)
}).finally(()=>{
})
}
}
},
mounted() {
this.getList()//跟正常调用函数一样的
}
}
如果是箭头函数,我们可以这样写:
this.$refs['weekForm'].validate((valid) => {
if (valid) {
this.$Modal.confirm({
title: '温馨提示',
content: '<p>确定要提交吗?</p>',
onOk: async () => {
let result1 = await this.getAuthCode()
let result2 = await this.getAccessToken(result1.data.authCode)
console.log('result1>>>', result1)
console.log('result2>>>', result2)
if (result1.data.code === 0 && result2.data.code === 0) {
this.$Message.success('成功')
}
},
onCancel: () => {
//this.nextStep = false
}
});
}
})
网友评论