Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Created May 16, 2012 19:03
Show Gist options
  • Save briancavalier/2713087 to your computer and use it in GitHub Desktop.
Save briancavalier/2713087 to your computer and use it in GitHub Desktop.
Use when.js to run tasks in sequence, parallel, on in a pipeline where the next task receives the result of the previous
var when = require('../when');
var delay = require('../delay');
/**
* Run array of tasks in sequence with no overlap
* @param tasks {Array} array of task functions
* @return {Array} result of each task will be in the
* array position corresponding to position of the
* task in the tasks array
*/
function sequence(tasks) {
return when.reduce(tasks, function(results, task) {
return when(task.call(null), function(result) {
results.push(result);
return results;
});
}, []);
}
/**
* Run array of tasks in parallel
* @param tasks {Array} array of task functions
* @return {Array} result of each task will be in the
* array position corresponding to position of the
* task in the tasks array
*/
function parallel(tasks) {
return when.map(tasks, function(task) {
return task.call(null);
});
}
/**
* Run array of tasks in a pipeline where the next
* tasks receives the result of the previous
* @param tasks {Array} array of task functions
* @return {*} return value of the final task
*/
function pipeline(tasks, initialValue) {
return when.reduce(tasks, function(value, task) {
return task.call(null, value);
}, initialValue);
}
// Some test tasks
function t1(x) {
return delay(arguments.length ? (x+1) : 1, 100);
}
function t2(x) {
return delay(arguments.length ? (x+1) : 2, 50);
}
function t3(x) {
return delay(arguments.length ? (x+1) : 3, 0);
}
// Example of running them in sequence, in parallel, and in a pipeline
when(sequence([t1, t2, t3]), function(results) { console.log('sequence', results); });
when(parallel([t1, t2, t3]), function(results) { console.log('parallel', results); });
when(pipeline([t1, t2, t3], 0), function(results) { console.log('pipeline', results); });
parallel [ 1, 2, 3 ]
sequence [ 1, 2, 3 ]
pipeline 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment