簡體   English   中英

延遲使用jQuery鏈接和排隊Ajax請求

[英]Chaining and queuing ajax requests using jQuery deferred

我有一個笨拙的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;
}

我沒有測試過,但是這個想法應該可行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM