Consim is a small module for NodeJS, that contains utility functions which gives you more control over how asynchronous callback functions are invoked on an array.
npm install consim
Executes next promise only after the preceding promise is resolved or rejected.
consim.series(arr, cb);
arr
is an array containing all the elements to be passed intocb
.cb
is a function that's executed for all elements inarr
.
const consim = require("consim");
const axios = require("axios");
consim.series([1, 2, 3, 4, 5], async num => {
const res = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${num}`
);
console.log(res.data);
});
Executes all promises at the same time. Doesn't work reliably when the input array gets large as node isn't able to handle it.
consim.parallel(arr, cb);
arr
is an array containing all the elements to be passed intocb
.cb
is a function that's executed for all elements inarr
.
const consim = require("consim");
const axios = require("axios");
consim.parallel([1, 2, 3, 4, 5], async num => {
const res = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${num}`
);
console.log(res.data);
});
Batches array into array of arrays first, then executes each batch in parallel, but all batches in series. Useful when the input array contains a large number of elements.
consim.batchedSeries(arr, cb, elementsPerBatch);
arr
is an array containing all the elements to be passed intocb
.cb
is a function that's executed for all elements inarr
.elementsPerBatch
an integer which determines how many requests run at the same time.
const consim = require("consim");
const axios = require("axios");
consim.batchedSeries(
[1, 2, 3, 4, 5],
async num => {
const res = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${num}`
);
console.log(res.data);
},
2
);
npm test