Javascript 函数等待返回直到 $.getJSON 完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10775787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:52:32  来源:igfitidea点击:

function wait with return until $.getJSON is finished

javascriptjqueryfunction

提问by xorinzor

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.

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

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:

但是,当使用 Chrome Javascript 控制台时,我可以看到:

  1. the function is called
  2. undefined is returned
  3. XHR request is finished
  4. variable thumbnail content is shown in console
  1. 该函数被调用
  2. 返回未定义
  3. XHR 请求完成
  4. 可变缩略图内容显示在控制台中

This is obviously the wrong order.

这显然是错误的顺序。

Any help is greatly appreciated!

任何帮助是极大的赞赏!

回答by Joseph

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 a thenwhich allows you to alter the resolved value.

getJSON返回一个承诺(一个只读的延迟),所以你可以听它。但是由于您需要进行一些后处理,因此您需要链接 athen以更改解析值。

// 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

原答案

You can use a deferred object, and listen for the done().

您可以使用延迟对象,并侦听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!
    });

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 to getThumbnail():

您可以 return $.getJSON's deferred 以获取原始数据。但是由于“后处理”到对象中,需要自定义延迟。您还可以将回调传递给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!
})

回答by thecodeparadox

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

您可以简单地使用$.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);

   });
}

NOTE:

笔记:

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

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