How to use async/await in Vue.js? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to use async/await in Vue.js? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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

We are here to answer your question about How to use async/await in Vue.js? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji