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.

1
  • 3
    getA doesn't return the promise. Commented Mar 2, 2019 at 5:11

4 Answers 4

71

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

Sign up to request clarification or add additional context in comments.

1 Comment

since getB is not asynchronous, then what is the use of async for getB ?
16

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

2 Comments

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.
it still feels like the way to go, you are awaiting for a promise that ends when console.log(1) run
9

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');
          });
      });
    },
  },

1 Comment

I think this is the best answer because it includes the vital error handling. My only change would be to use (reject(new Error('error message')); rather than resolve('rejected'); in the catch block.
7

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

1 Comment

adding async to created lifecycle method made it work for me while having a chained promises procedure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.