Javascript 使用jQuery延迟链接和排队ajax请求
我有一个笨重的ajax队列,它使用setTimeout和一个全局标志:Javascript 使用jQuery延迟链接和排队ajax请求,javascript,jquery,ajax,jquery-deferred,Javascript,Jquery,Ajax,Jquery Deferred,我有一个笨重的ajax队列,它使用setTimeout和一个全局标志: var InProgress = false; function SendAjax(TheParameters) { if (InProgress) { setTimeout(function () { SendAjax(TheParameters) } , 500) } InProgress = true; $.ajax({ ... data: TheParameters
var InProgress = false;
function SendAjax(TheParameters) {
if (InProgress) {
setTimeout(function () { SendAjax(TheParameters) } , 500)
}
InProgress = true;
$.ajax({
...
data: TheParameters,
complete: InProgress = false
});
}
我如何使用排队机制重写它,以便请求按照接收顺序一个接一个地触发?通过使用
,我们可以在每个请求进入时按顺序链接它们
var previousPromise;
// This actually sends the request
function actualSender(params) {
return $.ajax(...);
}
// This will make sure that the next request will be fired
// when the previous one finishes.
function SendAjax(TheParameters) {
if (previousPromise) {
// Even if the previous request has finished, this will work.
previousPromise = previousPromise.then(function () {
return actualSender(TheParameters);
});
return previousPromise;
}
// first time
previousPromise = actualSender(TheParameters);
return previousPromise;
}
我没有测试这一点,但是这个想法应该有效通过使用然后
我们可以在每个请求进入时按顺序链接它们
var previousPromise;
// This actually sends the request
function actualSender(params) {
return $.ajax(...);
}
// This will make sure that the next request will be fired
// when the previous one finishes.
function SendAjax(TheParameters) {
if (previousPromise) {
// Even if the previous request has finished, this will work.
previousPromise = previousPromise.then(function () {
return actualSender(TheParameters);
});
return previousPromise;
}
// first time
previousPromise = actualSender(TheParameters);
return previousPromise;
}
我没有对此进行测试,但这个想法应该可行如果同时出现多个请求,会发生什么?排队请求数组不是会更好吗?不会,因为承诺会被链接起来。我总是对jquery的简单功能感到惊讶。让我测试一下,我会回来的。它实际上是承诺这是否意味着行previousPromise=previousPromise。然后(..)向现有承诺添加一个承诺?如果同时出现多个请求,会发生什么情况?排队请求数组不是会更好吗?不会,因为承诺会被链接起来。我总是对jquery的简单功能感到惊讶。让我测试一下,我会回来的。它实际上是承诺这是否意味着行previousPromise=previousPromise。然后(…)将一个承诺添加到现有承诺中?