Create batches of cancelable requests and resolve them in one go.
Since this module uses async/await, Node.js v8.x or higher is required.
npm i @slimopgewekt/batchfetch
or
yarn add @slimopgewekt/batchfetch
const BatchFetch = require('@slimopgewekt/batchfetch');
const createBatch = () => {
const requests = [];
for(let i = 0; i < 50; i++) {
requests.push({url: `https://jsonplaceholder.typicode.com/posts/${i}`});
}
requests.push(
{
url: 'https://jsonplaceholder.typicode.com/posts',
options: {
method: 'POST',
data: {
userId: 1,
postId: 1,
title: 'So... About the avengers',
body: 'There are a lot of them...'
}
}
}
);
return BatchFetch.createBatch(requests);
};
async (batch, singleResultCallback) => {
return await batch.start(singleResultCallback);
};
singleResultCallback
is called every time a single request is finished, with its data.
The results of all requests are return in a single array by batch.start, hence the await
and return
.
To cancel the batch, call batch.cancel();
.
It'll cancel all the ongoing requests, batch.start
wont return anything, nor will the single result callbacks fire.