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.
To use async and await in Vue. js, we can add async and await in our component methods and hooks. to make the created hook an async method. We use await to wait for the getA method to finish before running the rest of the code.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
This allows the server to pre-render the component before sending it to the client and it allows the client to pre-fetch data before the new component is shown to the user.
Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.
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
Unlike what @thanthu said, you can use both then and await.
In your first post you only missed to add return
in the getA
method:
async created (){
await this.getA()
console.log(2)
await this.getB()
},
methods : {
getA() {
return $axios
.post(`/getA`,params){
.then((result) => {
console.log(1)
});
},
getB() {
console.log(3)
}
}
try this
async created (){
let resultFromgetA = await this.getA()
console.log(2)
await this.getB()
},
methods : {
getA :() =>{
return $axios.post(`/getA`,params);
},
getB : async() =>{
//use await key with async calls
console.log(3)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With