How to use async/await in Vue.js?
Asked Answered
C

4

44

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.

Convulsion answered 2/3, 2019 at 5:10 Comment(1)
getA doesn't return the promise.Flyblown
E
68

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

Ediva answered 2/3, 2019 at 5:26 Comment(1)
since getB is not asynchronous, then what is the use of async for getB ?Yellowtail
I
15

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)
    }
}
Intracardiac answered 26/8, 2019 at 13:21 Comment(2)
you can. But should you? one day you will find yourself in the middle of try-catch and .catch(err => {console.log(err)}) blocks, with tons of async-await and .then and .all instructions. It could be the second most difficult challenge for a gentleman. Of course, after an attempt to give birth to a baby. For women - the most difficult one.Wintery
it still feels like the way to go, you are awaiting for a promise that ends when console.log(1) runAloisius
L
8

Vuejs, example with Axios API request. more details between the code

  methods: {
    async getA(data, type) {
      console.log("This is a API calls, that the response time is vary.");

      const result = await this.getSources();
      
      console.log("Do what you want after completing the prev job.");
    },
    getSources() {
      return new Promise(resolve => {

        // Here the point is the resolve that you should resolve('something');.
        this.axios
          .get("/api/sources")
          .then((resp) => {
            this.sources = resp.data;
            resolve('resolved');
          })
          .catch(() => {
            resolve('rejected');
          });
      });
    },
  },
Leopardi answered 1/5, 2021 at 7:57 Comment(0)
T
6

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)
    }
}
Theocracy answered 2/3, 2019 at 5:15 Comment(1)
adding async to created lifecycle method made it work for me while having a chained promises procedure.Conceal

© 2022 - 2024 — McMap. All rights reserved.