0

I need help trying to upload items to an API using superagent.

The limit for items in a single upload is 500. So if I've to send more than 500 items, I've to break the request down into 3 separate requests if the upload size is 500, for example.

I've broken the request down, but now I'm wondering how make multiple requests to the API.

Any idea how to chain this using superagent? I've looked into multi-part uploads, but I don't know if this is the same thing.

Wasif Hyder
  • 1,309
  • 2
  • 10
  • 17
  • 1
    Not sure about `superagent`, you should be able to use `.then()` chained to `fetch()` calls – guest271314 Feb 27 '17 at 22:27
  • @guest271314 - Thanks, but I want to do it on an array of arrays. Is there a way to programmatically do that? – Wasif Hyder Feb 27 '17 at 22:37
  • 1
    Yes, see [multiple, sequential fetch() Promise](http://stackoverflow.com/questions/38034574/multiple-sequential-fetch-promise/); note, the pattern is considered "scheduling", not "recursion". Do you mean fifteen-hundred requests? Or three requests? Do requests need to be made in sequential order? – guest271314 Feb 27 '17 at 22:41
  • Three requests, but the order isn't important. – Wasif Hyder Feb 27 '17 at 22:44

1 Answers1

1

You can use Array.prototype.shift(), .then() to schedule call to a function if array containing arrays .length evaluates to true, else return array of responses. Which performs the process in sequence.

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));

Note, if order is not a part of requirement, you can substitute Promise.all(), Array.prototype.map() for .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));
guest271314
  • 1
  • 15
  • 104
  • 177