I am writing a function which has to get the thumbnail information from a given video using the embed.ly API, however currently the function returns a value before it even got the JSON result from the API.
I am using the following code:
function getThumbnail(vUrl) {
var thumbnail = '';
var title = '';
var caption = '';
var content = '';
$.when( $.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl) ).then(function(data){
var thumbnail = data.thumbnail_url;
console.log(thumbnail);
return {
thumbnail:thumbnail,
vurl:vurl
}
});
}
However when using the Chrome Javascript console I can see that:
- the function is called
- undefined is returned
- XHR request is finished
- variable thumbnail content is shown in console
This is obviously the wrong order.
Any help is greatly appreciated!
Updated answer
getJSONreturns a promise (a read-only deferred), so you can listen to it. But since you need some post-processing, you’d want to chain athenwhich allows you to alter the resolved value.Original answer
You can use a deferred object, and listen for the
done().You could return
$.getJSON‘s deferred to get the raw data. But because of “post-processing” into an object, the custom deferred is needed. You could also pass a callback togetThumbnail():