使用 jQuery 延迟链接和排队 ajax 请求
Chaining and queuing ajax requests using jQuery deferred
我有一个使用 setTimeout 和全局标志的笨重 ajax 队列:
var InProgress = false;
function SendAjax(TheParameters) {
if (InProgress) {
setTimeout(function () { SendAjax(TheParameters) } , 500)
}
InProgress = true;
$.ajax({
...
data: TheParameters,
complete: InProgress = false
});
}
我如何使用排队机制重写此代码,以便请求按接收顺序依次触发?
通过使用 then
我们可以在每个请求进入时按顺序链接它们。
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;
}
我没有测试这个,但这个想法应该可行
我有一个使用 setTimeout 和全局标志的笨重 ajax 队列:
var InProgress = false;
function SendAjax(TheParameters) {
if (InProgress) {
setTimeout(function () { SendAjax(TheParameters) } , 500)
}
InProgress = true;
$.ajax({
...
data: TheParameters,
complete: InProgress = false
});
}
我如何使用排队机制重写此代码,以便请求按接收顺序依次触发?
通过使用 then
我们可以在每个请求进入时按顺序链接它们。
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;
}
我没有测试这个,但这个想法应该可行