Javascript JQuery延迟了如何使用resolve和promise来确定函数结束
我想在JQuery函数运行时在html页面中显示一个微调器。因为它是异步的,所以我尝试使用deferred来确定函数何时完成 html页面中的代码Javascript JQuery延迟了如何使用resolve和promise来确定函数结束,javascript,jquery,Javascript,Jquery,我想在JQuery函数运行时在html页面中显示一个微调器。因为它是异步的,所以我尝试使用deferred来确定函数何时完成 html页面中的代码 var req = jslongfunc(value); req.done(function( response){ spinner.stop(); }); JS页面中包含jslongfunc的代码 function jslongfunc() { rdef = $.Deferred(); $.getJSON(
var req = jslongfunc(value);
req.done(function( response){
spinner.stop();
});
JS页面中包含jslongfunc的代码
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。我做错了什么?这里有一个我用来点击谷歌金融API进行股票报价的小程序
我在发送之前添加了Ajax事件,完成后可以关闭和打开一些设备(此调用的时间非常短)
但这可能会给你一个开始
编辑:这里是第二个更紧凑的代码
JS
仅当setTimeout函数在4500ms后调用
r.resolve()
时,您的承诺才是解析。完成所有工作后,需要调用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
});
r正在返回。但由于设置超时,只有在4500后才能“解决”。只有在承诺得到解决后,才会要求“完成”,而不是在承诺被退回时,我该如何实现承诺?如果我删除setTimeout,则永远不会调用done。为什么会有超时?是“很多东西”异步代码还是长时间运行的本地代码?@Alnitak在该块中有一些.getJSon调用是异步的。我已经暂停了,因为已经完成的将不会以其他方式执行。谢谢你的回答!我尝试了您的代码和微调器。stop()从不点击SSO微调器。stop()从不点击,jslongfunc是否完成执行?是的,但微调器一直在运行,因此我假设从未调用过“完成”。您是否从
.fail
回调中得到任何信息?尝试从fail回调中发出警报(“oops”),看看它是否是您的jslongfunc
函数。我在其中添加了警报。fail似乎也没有出现
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
});