我有FormData个对象数组,我想将它们发布到相同的URL。我想一次创建固定数量的AJAX请求,为此,我想创建xhr对象池。怎么做?
最佳答案
您可以使用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
。