VueJS get value from an axios promise

I have this code

Template :

<a href="#" class="video" @click.prevent="checkVideo(subItem.id)" :id="subItem.id" data-toggle="modal" data-target="#playerModal">{{subItem.name}}<span>{{getDuration(subItem.id)}}</span></a>

VueJS Function :

async getDuration(id) {
    var duration  = '';
    await axios.post('/api/v1/checkvideo', {
    menu: id
    })
    .then(function (response) {
    console.log(response.data[0].datas.duration)
    return response.data[0].datas.duration;
    });

    //console.log(duration);
    //return duration;
},

The problem is that the console.log show the values as expected but on the Vue Rendering I get this [object Promise] I want to know how to show the values after the promise has been resolved.

Thanks for helping

Upvotes: 4

Views: 14127

Answers (1)

bcjohn
bcjohn

Reputation: 2523

Your code is return axios which is a promise object. If you want to return final duration. You should await axios promise and return the response.

async getDuration(id) {
  var duration  = '';
  const response = await axios.post('/api/v1/checkvideo', {
    menu: id
  })
  return response.data[0].datas.duration;
}

EDITED

Since async return a promise, [object Promise] will always be rendered on the screen. If you want to get duration on a specific id, I think this is correct to do.

data() {
  return {
    id: null, // Maybe you should store the value of `id` here
    duration: null
  }
},
mounted() {
  this.getDuration(this.id)
},
methods: {
  async getDuration(id) {
    var duration  = '';
    const response = await axios.post('/api/v1/checkvideo', {
      menu: id
    })
    this.duration = response.data[0].datas.duration;
  }
}

Upvotes: 6

Related Questions