我有一个笨拙的ajax队列,它使用setTimeout和一个全局标志:
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;
}
我没有测试过,但是这个想法应该可行