我有一个使用setTimeout和全局标志的笨重的ajax队列:
var InProgress = false;
function SendAjax(TheParameters) {
if (InProgress) {
setTimeout(function () { SendAjax(TheParameters) } , 500)
}
InProgress = true;
$.ajax({
...
data: TheParameters,
complete: InProgress = false
});
}
如何使用排队机制重写此命令,以便请求按照收到的顺序依次触发?
答案 0 :(得分:1)
通过使用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;
}
我没有对此进行测试,但这个想法应该可行