javascript - JQuery Deferred如何使用resolve和promise来判断函数结束

标签 javascript jquery

我有一个 html 页面,我想在 JQuery 函数运行时显示一个微调器。由于它是异步的,我尝试使用 deferred 来确定函数何时完成

html页面中的代码

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

包含jslongfunc的JS页面中的代码

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

无论 jslongfunc 何时完成其所有代码,微调器似乎都会运行 4500。我知道它什么时候结束,因为它画了一些东西。我认为如果函数在超时之前完成, r 将返回并且 .done 将执行。我做错了什么?

最佳答案

当您的 setTimeout 函数在 4500 毫秒后调用 r.resolve() 时,您的 promise 才会得到解决。当所有的事情都完成后,你需要调用r.resolve()。也许是这样的......

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

更新

现在您已经使用了 $.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
});

关于javascript - JQuery Deferred如何使用resolve和promise来判断函数结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25128136/

相关文章:

javascript - 查找与给定数字最接近的数字之和

javascript - 如何使 div 匹配动态创建的谷歌图表高度

jquery - 动态添加的按钮(使用 jQuery)必须单击两次才能触发已绑定(bind)到按钮的单击事件

javascript - 使用上一页和下一页按钮制作我自己的滑动图片库

javascript - jQuery 不调用警报框

javascript - 如何在 JavaScript 中将字符串转换为 XML 对象?

javascript - 希腊字符串转小写

javascript - 如何使用 css 列属性调整 <ul> 中的下拉菜单项?

javascript - 使用 jQuery 停止 CSS 动画?

php - 选择多个不起作用