如何在 Vue.js 中使用 async/await? [英] How to use async/await in Vue.js?
本文介绍了如何在 Vue.js 中使用 async/await?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 ES7 新手
我想在 Vue.js 中使用 async/await
I want to use async/await in Vue.js
这是我的代码
created (){
this.getA()
console.log(2)
this.getB()
},
methods : {
getA (){
console.log(1)
},
getB (){
console.log(3)
}
}
它返回
1
2
3
但是当我将它与 axios 一起使用时,则
But when I use it with axios, then
created (){
this.getA()
console.log(2)
this.getB()
},
methods : {
getA (){
$axios.post(`/getA`,params){
.then((result) => {
console.log(1)
})
},
getB (){
console.log(3)
}
}
它返回
2
3
1
所以我想在该代码中添加 async/await.
So I want to add async/await in that code.
如何使用异步/等待?
我试过了
async created (){
await this.getA()
console.log(2)
await this.getB()
},
methods : {
getA (){
$axios.post(`/getA`,params){
.then((result) => {
console.log(1)
})
},
getB (){
console.log(3)
}
}
它返回相同的结果.
推荐答案
您必须使用 then
或 await
之一,不能同时使用,如下所示:
You have to use either then
or await
not both as shown below:
如果使用 then
created () {
this.getA().then((result) => {
console.log(1)
console.log(2)
this.getB()
})
},
methods : {
getA () {
return $axios.post(`/getA`,params);
},
getB (){
console.log(3)
}
}
如果使用await
async created (){
await this.getA()
console.log(1)
console.log(2)
this.getB()
},
methods : {
getA : async() => {
return $axios.post(`/getA`,params);
},
getB : () => {
console.log(3)
}
}
请注意,在调用 getB() 时,您不需要 then
或 await
,因为它不是异步的
Note that while calling getB() you don't need then
or await
since it is not asynchronous
这篇关于如何在 Vue.js 中使用 async/await?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文