2

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 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Thanks for you answer. How would i pass userName in html since i am calling the function there.
You can pass username to html as mentioned in the div, initially it'll be blank and when the getUser method is called username value will get updated and Vue will re-render the updated username in the view (html).

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.