Node Each

N(ode) E(each)
If you are doing 'heavy lifting' loops in Node.js you can fork and allocate a new thread. But what if you want to run the loop in the same process and distribute iterations through multiple Event Loop cycles?
Node Each is here to solve the later. It avoids blocking Node.js Event Loop while performing asynchronous and intensive for each loops. It allows to set next iteration to be run on the next Event Loop cycle, giving the opportunity for Node to process queued events.
Install
$ npm install node-each
var ne = require('node-each');
Usage
ne.each(Array, [Callback], [Options])
Array: [*]
Array to run each loop.
Callback: Function(el, i)
- e{*} - iteration element
- i{Number} - iteration index
If the callback function returns a Promise back to the iterator handler, the next iteration will only run after Promise fulfilment.
Options: Object{debug, on, when}
- debug{Boolean} - debug flag (default: false)
- on{String} - iteration or time (default: iteration)
- when{Number} - total iteration or total time in milliseconds (decimal allowed) to trigger next cycle (default: 1)
Trigger next Event Loop cycle iteration based 'on' iteration number or time in milliseconds since the last cycle.
By default it will trigger based 'on' iteration every time it reaches 'when', in this case 1. Simply put on every loop iteration.
NE uses process.hrtime() to calculate time, so decimals can be used to work with smaller units.
Returns: Promise{fulfilled(debug)}
Debug: Object{average, cycles, duration, iterations, on, when}
- average{Number} - average iteration time (ms)
- cycles{Number} - each total cycles
- duration{Number} - each duration time (ms)
- iterations{Number} - each iterations
- on{String} - each on setting
- when{String} - each when setting
ne.stats
Object{executing}: Number
- executing{Number} - number of each loops running at this moment
Examples
var ne = require('node-each');
var names = ['Helen', 'John', 'Peter', 'Jim'];
On: Iteration
var options = {
debug: true
};
ne.each(names, function(el, i){
console.log('Name', el + ' has index of ' + i);
}, options).then(function(debug) {
console.log('Finished', debug);
});
On: Time
var options = {
debug: true,
on: 'time',
when: 150.000001
};
ne.each(names, function(el, i){
return new Promise(function(resolve) {
setTimeout(function(){
console.log('Name', el + ' has index of ' + i);
console.log('Loops executing', ne.stats.executing);
resolve();
}, 100);
});
}, options).then(function(debug) {
console.log('Finished', debug);
console.log('Loops executing', ne.stats.executing);
});
Dependency
Bluebird
Contribute
Node Each module uses semantic-release with Commit Guidelines.
$ mkdir node-each && cd node-each
$ git clone git@github.com:goncaloneves/node-each.git .
$ npm install
$ npm test
$ npm run commit
$ gulp
$ gulp lint
$ gulp test
License
MIT License
2015 © Gonçalo Neves