gpt4 book ai didi

javascript - 使用 jQuery deferred 链接和排队 ajax 请求

转载 作者:行者123 更新时间:2023-12-02 14:28:29 25 4
gpt4 key购买 nike

我有一个笨重的 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;
}

我没有对此进行测试,但这个想法应该可行

关于javascript - 使用 jQuery deferred 链接和排队 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38038903/

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