简体   繁体   English

jQuery Deferred如何使用resolve和Promise确定函数结束

[英]JQuery Deferred how to use resolve and promise to determine function end

I have a in an html page that I'd like to show a spinner on while a JQuery function is running. 我在html页面中有一个想要在运行JQuery函数时显示微调器的页面。 Since its asynchronous I am trying to use deferred to determine when the function completed 由于它是异步的,因此我尝试使用deferred来确定函数何时完成

the code in the html page html页面中的代码

 var req = jslongfunc(value);
 req.done(function( response){
           spinner.stop();
 });

The code in the JS page that contains jslongfunc JS页面中包含jslongfunc的代码

function jslongfunc() {
   rdef = $.Deferred();
   $.getJSON('mycode, function(data){
   ... do lots of stuff here ...
  });
  setTimeout(function () {
             r.resolve();
        }, 4500);
   return r.promise();

The spinner seems to run for 4500 regardless of when the jslongfunc finished all its code. 无论jslongfunc何时完成所有代码,微调器似乎都可以运行4500。 I know when it finishes because it draws something. 我知道它什么时候完成,因为它会绘制一些东西。 I thought r would return and .done would execute if the function finished before the time out. 我以为如果功能在超时之前完成,r将返回并且.done将执行。 What am I doing wrong? 我究竟做错了什么?

Your promise is resolving only when your setTimeout function is calling r.resolve() after 4500ms. 当setTimeout函数在4500ms之后调用r.resolve()时,您的诺言才得以解决。 You need to call r.resolve() when all your stuff is done. 完成所有工作后,您需要调用r.resolve() Maybe something like this... 也许是这样的...

// function definition
var jslongfunc = function(defr) {
    //... do lots of stuff here ...
    defr.resolve();
}

// promise helper
var promise = function (fn) {
    var dfd = $.Deferred(fn);
    return dfd.promise();
}
// init the deferred by using the promise helper above and then attach 'done' callback to stop spinner
var rdef = promise(jslongfunc).done(function (response) {
    spinner.stop();
}).fail(function (response) {
    // handle promise failure.
});

Update 更新

Well now that you put up your using $.getJSON you can do the following. 好了,现在您使用$.getJSON您可以执行以下操作。

function jslongfunc(value) {
  var jqxhr = $.getJSON(url, function (data) {
    // THIS IS YOUR FIRST promise callback
    // do some stuff with the json you just got
  });
  // return the promise
  return jqxhr;
}

// now handle the spinner stoppage
jslongfunc(value).done(function () {
  spinner.stop();
}).fail(function (data) {
  // handle function failure here
});

Here is a little FIDDLE that I use to hit the Google financial API for stock quotes. 这是我用来点击Google Financial API进行股票报价的小技巧

I've added the Ajax events beforesend, complete that turns some gears off and on (very short period of time for this call). 我在事前添加了Ajax事件,完成该操作后会打开和关闭某些设备(此调用的时间很短)。

But it will probably give you a start. 但这可能会给您一个开始。

Edit: Here's a second FIDDLE with more compact code. 编辑:这是第二具有更紧凑代码的FIDDLE

JS JS

$('.putmehere1').hide();
var quotevalue;
var symboltopass = "NYSE:SDY";

$.ajax({
         type: "GET",
          url: "https://finance.google.com/finance/info",
        async: false,
     dataType: 'JSONP',
         data: {
                client: 'ig',
                     q: symboltopass
                }
 })
.done( function(data){
                                 var stockInfo = data[0];
                                 console.log( data[0] );
                                 quotevalue = stockInfo.l;
                                 $('.putmehere2').html( '#2 - ' + quotevalue);
                          });
$.ajax({
   beforeSend: function(){
      $('.putmehere1').show();
   },
   complete: function(){
      $('.putmehere1').hide();
   }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM