【问题标题】:Chaining and queuing ajax requests using jQuery deferred使用 jQuery deferred 链接和排队 ajax 请求
【发布时间】:2016-06-26 13:24:00
【问题描述】:

我有一个使用 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】:

    通过使用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;
    }
    

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

    【讨论】:

    • 如果同时有多个请求会发生什么?队列中的请求数组不是更好吗?
    • 不,因为承诺被锁住了。
    • 我总是对 jquery 的简单性感到惊讶。让我测试一下,我会回来的。
    • 实际上是承诺。 ;)
    • 这是否意味着previousPromise = previousPromise.then(..) 行在现有promise 中添加了promise?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    相关资源
    最近更新 更多