0

I'm trying to store in a variable the duration of a vimeo video using the API.

here is my code :

var iframe = document.querySelector('iframe');
var player = new Vimeo.Player(iframe);

var duree = player.getDuration().then(function(duration) {
    // duration = the duration of the video in seconds
}).catch(function(error) {
    // an error occurred
});

console.log(duree);

when I console.log my variable "duree", here is what I get :

Promise { <state>: "pending" }

the only way to get the duration in my console is to add console.log(duration); inside my function.

like this :

var duree = player.getDuration().then(function(duration) {
    console.log(duration);
}).catch(function(error) {
    // an error occurred
});

console.log(duree);

I don't understand what I am doing wrong, I only want to store the duration inside my variable "duree".

can anybody help me with this ?

thanks

mmdwc
  • 1,095
  • 6
  • 27
  • 53
  • that is because it's async operation and you can only get the result `duration` once the Promise is in `Fulfilled` status then only the `.then()` handler is called , you are getting `Pending` status because the Promise it not fulfilled yet. One way to assign the value of `duration` would be `var duree = duration` inside the `.then()` where you have the `console.log` – Niladri Nov 14 '17 at 18:24
  • @Niladri thanks, but when adding this inside : player.getDuration().then(function(duration) { var duree = duration; }).catch(function(error) { // an error occurred }); console.log(duree); I get nothing in my console. do you know why ? – mmdwc Nov 14 '17 at 18:32
  • this post has a nice explanation https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Niladri Nov 14 '17 at 18:33
  • it is because of aync nature of Promise when your console.log runs at that time the value is not available . hence it is recommended to do the operation you need to do inside the `.then()` handler only. The value is not available outside . With your current code you still have to do `duree.then(function(data){ console.log(data)})` to get the value but still inside `then()` as duree is a Promise itself. – Niladri Nov 14 '17 at 18:36

0 Answers0