Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  176] [ 1]  / answers: 1 / hits: 132185  / 5 Years ago, sat, march 2, 2019, 12:00:00

I'm new in ES7



I want to use async/await in Vue.js



Here is my code



created (){
this.getA()
console.log(2)
this.getB()
},
methods : {
getA (){
console.log(1)
},
getB (){
console.log(3)
}
}


It returns



1
2
3


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)
}
}


It returns



2
3
1


So I want to add async/await in that code.



How can I use async/await?



I tried



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)
}
}


It returns same result.


More From » vue.js

 Answers
8

You have to use either then or await not both as shown below:


If using 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)
}
}

If using 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)
}
}

Note that while calling getB() you don't need then or await since it is not asynchronous


[#52500] Tuesday, February 26, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;