Vue How to return value from async/await function?

Viewed 1967

I am calling an async function in my html. But it's returning a promise. How can I display the value from the aysnc function?

<div>
    {{ getUser(userId) }}
</div>
async getUser(userId) {
    try {
        const res = await this.getUser(userId);
        const userName = res.data.name;
        return userName
    } catch (error) {}
},
2 Answers

One of the easiest way to handle this is to create a data variable in Vue and let Vue re-render the variable on promise completion.

<div>
   {{ username }}
</div>

data(){
  return {
    username: ''
  }
}

methods: {
 async getUser(userId) {
     try {
        const res = await this.getUser(userId);
        this.username = res.data.name;
     } 
     catch (error) {
        this.username = 'Oh oh , something went wrong' // optional
     }
  },
}

In VueJs you can bind your data from a request to the data

So in the example below I'll comment how you can do it:

<template>
   <div>
      <span>{{ user.username }}</span>
      <button @click="getUser(// The user Id)">Click me to get User</button>
   </div>
</template>

<script>
export default {
   data(){
      user:{
         username: "",
      },
   },
   methods:{
      async getUser(userId){
            const res = await this.getUser(userId);
            // Set response on the user registered in data
            this.user.username = res.data.name;
            // Now that you have set the username on the user object
            // You can approach it with {{user.username}}
      }
   }
};
</script>
Related