stepper
Stepper and Grouper classes for running an arbitrary number of tasks in series or parallel
Motivation
Eliminate some boilerplate when using step.
Usage
- Create a
stepper
- Register listeners for any events you're interested in
- Add some functions using stepper's
add()
method - Call stepper's
walk()
method
Examples
Running some sync and async tasks one after another
var Stepper = require('../lib/stepper').Stepper;
var stepper = new Stepper();
// add steps
stepper.add(function(err, val) {
console.log('running step 1 (sync)');
return 1;
});
stepper.add(function(err, val) {
if (err) throw err;
console.log('running step 2 (sync)');
return 2;
});
stepper.add(function(err, val) {
if (err) throw err;
console.log('running step 3 (async)');
var self = this;
console.log('wait 2 seconds...');
setTimeout(function() {
console.log('completed step 3 (async)');
self();
}, 2000);
});
stepper.add(function(err, val) {
console.log('running step 4 (sync)');
return 4;
});
// handle completion
var onComplete = function(err, val) {
if (err) throw err;
console.log('stepping is complete');
console.log('return value: ' + val + '\n');
};
// run steps
console.log('\nstart stepping...');
stepper.walk(onComplete);
Output
start stepping...
running step 1 (sync)
running step 2 (sync)
running step 3 (async)
wait 2 seconds...
completed step 3 (async)
running step 4 (sync)
stepping is complete
return value: 4
Run some async tasks in parallel
var Grouper = require('../lib/stepper').Grouper;
var grouper = new Grouper();
// setup group functions
grouper.add(function(fn) {
console.log('running step 1 (async)');
console.log('wait 3 seconds...');
setTimeout(function() {
console.log('completed step 1 (async)');
fn(null, 1);
}, (1000 * 3));
});
grouper.add(function(fn) {
console.log('running step 2 (async)');
console.log('wait 2 seconds...');
setTimeout(function() {
console.log('completed step 2 (async)');
fn(null, 2);
}, (1000 * 2));
});
grouper.add(function(fn) {
console.log('running step 3 (async)');
console.log('wait 1 second...');
setTimeout(function() {
console.log('completed step 3 (async)');
fn(null, 3);
}, (1000));
});
// handle completion
var onComplete = function(err, vals) {
if (err) throw err;
console.log('group is complete');
console.log('return values: ' + vals + '\n');
};
// run steps
console.log('\nstart group...');
grouper.walk(onComplete);
Output
start group...
running step 1 (async)
wait 3 seconds...
running step 2 (async)
wait 2 seconds...
running step 3 (async)
wait 1 second...
completed step 3 (async)
completed step 2 (async)
completed step 1 (async)
group is complete
return values: 1,2,3
You can also add()
Stepper
s and Grouper
s. See examples/nesting.js
Credits
Inspired by and dependent on step