[英]JQuery Deferred how to use resolve and promise to determine function end
我在html頁面中有一個想要在運行JQuery函數時顯示微調器的頁面。 由於它是異步的,因此我嘗試使用deferred來確定函數何時完成
html頁面中的代碼
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將執行。 我究竟做錯了什么?
僅當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
});
這是我用來點擊Google Financial API進行股票報價的小技巧 。
我在事前添加了Ajax事件,完成該操作后會打開和關閉某些設備(此調用的時間很短)。
但這可能會給您一個開始。
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.