使用jQuery链接和排队Ajax请求延期

问题描述 投票:0回答:1

我有一个使用setTimeout和全局标志笨重的AJAX队列:

var InProgress = false;

function SendAjax(TheParameters) {

  if (InProgress) {
     setTimeout(function () { SendAjax(TheParameters) } , 500) 
  }

  InProgress = true;

  $.ajax({
    ...
    data: TheParameters,
    complete: InProgress = false
  });
}

我怎么可以重写这个使用排队机制,使请求触发一个顺序的其他他们收到后?

javascript jquery ajax jquery-deferred
1个回答
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;
}

我没有测试这一点,但这个想法应该工作

© www.soinside.com 2019 - 2024. All rights reserved.