English 中文(简体)
函数使用return等待直到$.getJSON完成
原标题:function wait with return until $.getJSON is finished

我正在编写一个函数,该函数必须使用embed.ly API从给定的视频中获取缩略图信息,但目前该函数甚至在从API获得JSON结果之前就返回了一个值。

我正在使用以下代码:

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
        }
    });
}

然而,在使用Chrome Javascript控制台时,我可以看到:

  1. the function is called
  2. undefined is returned
  3. XHR request is finished
  4. variable thumbnail content is shown in console

这显然是错误的顺序。

非常感谢任何帮助!

最佳回答

Updated answer

getJSON返回一个promise(只读延迟),所以你可以监听它。但由于你需要一些后处理,你想先链上一个,然后链上

// Now using `then`
function getThumbnail(vUrl){
  return $.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl).then(function(data){
    return {
      thumbnail:data.thumbnail_url,
      vurl:vurl
    }
  });
}

//and in your call will listen for the custom deferred s done
getThumbnail( the_vurl_ ).then(function(returndata){
  //received data!
});

Original answer

您可以使用a延迟对象,并监听done()

function getThumbnail(vUrl) {
    //create our deferred object
    var def = $.Deferred();

    //get our JSON and listen for done
    $.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl)
        .done(function(data){

            //resolve the deferred, passing it our custom data
            def.resolve({
                thumbnail:data.thumbnail_url,
                vurl:vurl
            });
        });

    //return the deferred for listening
    return def;
}

//and in your call will listen for the custom deferred s done
getThumbnail( the_vurl_ )
    .done(function(returndata){
        //received data!
    });

您可以返回延迟的$.getJSON以获取原始数据。但由于对对象进行“后处理”,因此需要自定义延迟。您还可以将回调传递给getThumbnail()

function getThumbnail(vUrl,callback) {
    $.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl,function(returndata){
        callback(returndata);
    });
}

getThumbnail( the_vurl_ ,function(returndata){
    //received data!
})
问题回答

使用Async/Await

async function getThumbnail(vUrl) {
  const data = await $.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vUrl);
  return {
      thumbnail:data.thumbnail_url,
      vurl:vUrl
    }
}

async function someFunction() {
    let thumbNail = await getThumbnail( the_vurl_ );
}

您可以简单地使用$.getJSON的回调,如下所示:

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);

   });
}

注意:

你可以看到,我正在调用一个函数来传递结果,你试图返回,但你不能result返回给调用者函数。因为$.getJSON是异步的。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.