1.0.4 • Published 4 years ago
consim v1.0.4
Consim
Introduction
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.
Installation
npm install consim
Usage
Series
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
.
Example
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);
});
Parallel
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
.
Example
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);
});
Batched Series
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.
Example
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
);
Tests
npm test