Home > Back-end >  How to execute the function after the api call is completed in vue js?
How to execute the function after the api call is completed in vue js?

Time:01-22

i am new to vue js , i have a situation where i have to execute the function getUserViews() after the getUser api call is completed. but looks like the getUserViews is executing before the api call is fully completed.

       async initUserLogin() {
    
      await this.getAccountNumber();

      if (!this.userHasDetails) {
         this.getUser();
      }

    },

    mounted() {
    this.$store.commit(types.user.setLogIn);
    this.watchBreakpoints();
    this.getUserViews();
    if (this.loginUser) {
      this.initUserLogin();
    }
},

CodePudding user response:

You have to add await before this.getUser() (if this returns a promise)

Try also adding the get function after the async call. Then use .then(), this will be called when the request succeeded.

more info about async/await handling can be found here

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

async initUserLogin() {
    await this.getAccountNumber();
    if (!this.userHasDetails) {
       await this.getUser(); //if this returns a promise
    }
},

mounted() {
    this.$store.commit(types.user.setLogIn);
    this.watchBreakpoints();
    if (this.loginUser) {
      this.initUserLogin().then((response) => {
        this.getUserViews();
      })
    }
}

  •  Tags:  
  • Related