2017-02-08 103 views
0

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

+0

你是什么意思的“池”? –

+0

如果你在承诺中包装你的AJAX请求,你可以使用[这个答案](http://stackoverflow.com/questions/39863062/how-can-i-call-one-asynchronous-function-in-a-group-方式/ 39863245#39863245)来解决这个问题。 – SimpleJ

+0

按池我的意思是XMLHttpRequest对象的数组。 – user41451

回答

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再次调用如果任何元件在阵列剩余。