XMLHTTP请求的延迟

时间:2017-07-27 10:18:28

标签: javascript json foreach xmlhttprequest delay

有没有方便的方法在 Javascript 中制作XMLHTTP请求?在发送之前等待3秒?我有一个数组全名

var items = [
    { url: "www.google.com/getChocolate", name: "Chocholate"},
    { url: "www.google.com/getCake", name: "Cake"},
    { url: "www.google.com/getCookie", name: "Cookie"},
];

for (var i = 0; i < items.length; i++) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var data;
            data = JSON.parse(xhr.responseText);
            // processing data here
        }
    };
    xhr.open("GET", items[i].url, false);
    xhr.send();
    // I somehow have to force to send the request for each item only every 3 seconds
}

对于他们每个人,我想从服务器接收JSON响应,但如果我经常发送请求,它会禁止我,所以我需要每隔3秒发送一次,等待响应,处理响应和开始一个新的。 我想我必须让它同步,所以我已经在xhr.open中添加了错误的参数。

1 个答案:

答案 0 :(得分:1)

我是朋友,

我刚看到你的帖子,我明白你想做一个请求队列 - 在3秒后发送第一个请求并等待它完成然后发送下一个和下一个直到队列结束。

我制作了一个非常简单的课程RequestRequestManager,它会为你做这件事。

查看代码,如果您不清楚某些内容,请告诉我。尝试阅读评论。

var items = [{
    url: "www.google.com/getChocolate",
    name: "Chocholate"
  },
  {
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cake",
    name: "Cake"
  },
  {
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cookie",
    name: "Cookie"
  },
];

/* First prepare array of requests that later will be send */
var requests = [];
for (var i = 0; i < items.length; i++) {
  requests.push(new Request(items[i].url));
}

/* Initialize the object that will be responsible for 
 * request sending and process the requests  */
var manager = new RequestManager(requests);
manager.process();
manager.onSend(function(url, response) {
  /* this code will fire once a request is completed, no matter if success of failed */
  console.log('request to ' + url + ' completed ....');
  console.log('----------------------------------------');
})


/**
 * This class is a wrapper that will hold the request
 * and will be responsible to send it with a delay of 3 seconds
 * 
 * @param {string} url - this is the url which is going to be requested
 * @returns {Request} - new Request object
 */
function Request(url) {
  var that = this, resolve, reject;
  that.url = url;

  that.promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });

  that.xhr = new XMLHttpRequest();
  that.xhr.onreadystatechange = function() {
    if (that.xhr.readyState == 4) {
      if (that.xhr.status == 200) {
        var data = null;
        try {
          data = JSON.parse(that.xhr.responseText);
          resolve(data);
        } catch (e) {
          reject(e);
        }
      } else {
        reject({
          statusText: that.xhr.statusText,
          response: that.xhr.response
        });
      }
    }
  };

  that.send = function() {
    /* send request after 3 seconds */
    setTimeout(function() {
      that.xhr.open("GET", that.url, true);
      that.xhr.send();
    }, 3000)

    return this;
  }
}


/**
 * This class is responsible for processing all the request
 * The main role is to call the Request's send method, 
 * wait the request to complete and then call the next request from the queue
 * until all the requests are processed
 * 
 * @param {Array} requests - this is an array of Request objects
 * @returns {RequestManager} new RequestManager object
 */
function RequestManager(requests) {
  var that = this,
    callback;
  that.requests = requests;

  that.onSend = function(cb) {
    callback = cb;
  }

  that.process = function() {
    console.log('Starting requests sending .......');
    doRequestRecursive(that.requests.pop());
  }

  function doRequestRecursive(request) {
    request.send().promise.then(function(data) {
      console.log('request ' + request.url + ' success ...');
      callback(request.url, data);
    }, function(err) {
      console.log('request ' + request.url + ' failed ...');
      callback(request.url, err);
    }).then(function() {
      var nextRequest = that.requests.pop();
      if (nextRequest) {
        doRequestRecursive(nextRequest);
      }
    });
  }
}

示例代码段正在向维基百科发送请求,以证明它们正在成功,因为您的链接不起作用。