Skip to content

Instantly share code, notes, and snippets.

@mikermcneil
Created June 21, 2015 01:03
Show Gist options
  • Save mikermcneil/c2918a902bddf3e6830d to your computer and use it in GitHub Desktop.
Save mikermcneil/c2918a902bddf3e6830d to your computer and use it in GitHub Desktop.
example of reporting progress using machines + lamda inputs
// A machine definition
// (e.g. `machines/do-stuff.js`)
module.exports = {
friendlyName: 'Do stuff',
// ...
inputs: {
numBatches: {
description: 'The number of batches to process.',
example: 4,
required: true
},
onProgress: {
description: 'Optional function to call to report progress.'
example: '->'
}
},
// ...
fn: function (inputs, exits) {
var _ = require('lodash');
var async = require('async');
// Do a bunch of batches of things
var numFinished = 0;;
async.each(_.range(0,inputs.numBatches), function (i, next){
// TODO: do a batch o' stuff (pretending w/ setTimeout for now)
setTimeout(function afterBatchOStuffFinished(){
numFinished++;
// Report progress if a lamda function was provided
if (!_.isUndefined(inputs.onProgress)){
// Only report progress every fifth batch
if (numFinished % 5 === 0) {
inputs.onProgress({
statusMessage: 'all good, baby',
percentComplete: (numFinished/inputs.numBatches)*100
});
}
}
return next();
}, Math.floor(Math.random() * 1000) );
}, function afterwards(err){
if (err) {
return exits.error(err);
}
return exits.success();
});
}
};
var Example = require('machinepack-example');
Example.doStuff({
numBatches: 100,
onProgress: function (incoming){
console.log('Got a progress update! It has this message: "%s". Also looks like its %d% of the way done.',incoming.statusMessage, incoming.percentComplete);
}
}).exec({
error: function (err){
console.error('uh oh:',err);
},
success: function (){
console.log('sweet it worked');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment