AJAX请求池

时间:2017-02-08 17:35:14

标签: javascript ajax

我有FormData个对象的数组,我想将它们发布到相同的URL。我想一次制作固定数量的AJAX请求,因为我想创建xhr对象池。怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.splice()Promise.all()fetch()一次执行N次请求。

let data = [FormData, FormData, ..];

let N = 5;

let pool = data.splice(0, N);

let processData = requests => 
  Promise.all(
    requests.map(fd =>
      fetch("/path/to/server", {
        method: "POST",
        body: fd
      })
      .then(response => response.ok)
    )
  )
  .then(responses => responses.every(result => result))
  .then(result => {
    if (result) {
      if (data.length) {
        pool = data.splice(0, N);
        return true
      }
    }
    return "complete"
  });    

let fn = next => next === true ? processData(pool).then(fn) : next;

processData(pool)
.then(fn)
.then(complete => console.log(complete))
.catch(err => console.log(err));

jsfiddle https://jsfiddle.net/ce1kzu52/5/

如果数组中还有任何元素,您也可以在不调度函数processData的情况下处理数组。