function wait with return until $.getJSON is finished

前端 未结 3 1245
我在风中等你
我在风中等你 2020-12-05 05:07

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 g

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 05:26

    you can simple use $.getJSON's callback like following:

    function result(res) {
      console.log(res);
    }
    
    function getThumbnail(vUrl) {
       var thumbnail   = '';
       var title       = '';
       var caption     = '';
       var content     = '';
    
       $.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl, function(data) {
         var thumbnail = data.thumbnail_url;
         console.log(thumbnail);
    
         var result = {
            thumbnail:thumbnail,
            vurl:vurl
          };
    
         // passing the result to a function
         getResult(result);
    
       });
    }
    

    NOTE:

    You see that I'm calling a function to pass the result, where you are trying to return, but you can't return result to caller function. Because, $.getJSON is asynchronous.

提交回复
热议问题