我有一个 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/