使用POST API进行多部分表单上载

时间:2017-02-27 22:14:18

标签: javascript api superagent

我需要帮助尝试使用superagent将项目上传到API。

单次上传中的商品限制为500.因此,如果我发送的商品超过500件,我可以将请求分解为3个单独的请求,如果上传大小为500,例。

我已经打破了请求,但现在我想知道如何向API发出多个请求。

知道如何使用superagent链接这个吗?我已经查看了多部分上传文件,但我不知道这是否是同一件事。

1 个答案:

答案 0 :(得分:1)

如果包含数组Array.prototype.shift()的数组求值为.then(),则可以使用.lengthtrue来安排对函数的调用,否则返回响应数组。它按顺序执行该过程。

const requests = [[..], [..], [..]];
let results = [];
let request = requests.shift();
let handleRequests = (data) => fetch("/path/to/server", {
  method:"POST", body:data
})
.then(response => response.text())   
.then(res => {
  results.push(res);
  return requests.length ? handleRequest(requests.shift()) : results
});

handleRequest(request)
.then(res => console.log(res)
, (err) => console.log(err));

注意,如果订单不是要求的一部分,您可以将Promise.all()Array.prototype.map()替换为.shift()

let handleRequests = (data) => fetch("/path/to/server", {
  method:"POST", body:data
})
.then(response => response.text());
Promise.all(requests.map(handleRequests))
.then(res => console.log(res)
, (err) => console.log(err));
相关问题