gpt4 book ai didi

javascript - 在 jquery deferred 解析请求数组后总是调用一个 Action

转载 作者:行者123 更新时间:2023-11-30 06:29:38 24 4
gpt4 key购买 nike

我正在以循环方式从多个来源异步轮询数据,并希望在所有这些轮询完成后重复轮询。我正在尝试将 jQuery Deferred 对象与“始终”一起使用以重复我的轮询,如下面的代码所示:

function makeAjaxCall(region) {
var params = {
'action': POLLER.action,
},
url = POLLER.region_to_url[region];

return $.ajax({
dataType: "json",
url: url,
data: params,
success: (function(region) {
return function(result, status) {
handleAjaxResult(result, status, region);
};
})(region),
error: (function(region) {
return function(jqXHR, textStatus, errorThrown) {
handleAjaxError(jqXHR, textStatus, errorThrown, region);
};
})(region)
});
}

function nextPoll() {
if(!polling) {
return;
}

var requests = [];

$.each(POLLER.regions, function(i, region) {
requests.push(makeAjaxCall(region));
});

$.when.apply($, requests)
.always(function() {
log("deferred.always ", this)
updateSummary();
var delay = POLLER.POLLER_INTERVAL_MS;
if (delay != 0) {
pollerTimeout = setTimeout(nextPoll, delay);
}
}).fail(function() {
log("fail for ",this)
});
}

我的问题是,当我的一项民意调查失败时,将调用“始终” block 。我可能错误地假设“总是”应该在所有 请求完成或失败后调用。我打算让它以这种方式运行,因此任何关于不同的、也许更简单的方法的提示都会很棒。

最佳答案

我为 $.when 写了一个扩展,正是这样做的。

This extension treats all successes and failures as progress events. After all the promises have completed, the global promise is resolved if there were no errors. Otherwise the global promise is rejected.

$.whenAll - https://gist.github.com/4341799 ( tests )

示例用法:

$.whenAll($.getJSON('foo'), $.getJSON('bar'))
.then(
doneCallback
,failcallback
// progress callback
// the only problem is $.ajax.done/fail states call their callbacks
// with params in different locations (except for state)
,function(data, state, jqXhr) {
if (state == 'success') {
// do happy stuff
}
else { // error (fail)
// `data` is actually the jqXhr object for failed requests
// `jqXhr` is the text of the error "Not Found" in this example
}
}
)
;

关于javascript - 在 jquery deferred 解析请求数组后总是调用一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18591700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com