Skip to content

Instantly share code, notes, and snippets.

@smashingpat
Last active November 5, 2017 22:22
Show Gist options
  • Save smashingpat/b852d40638f07b08ff693b73692c1189 to your computer and use it in GitHub Desktop.
Save smashingpat/b852d40638f07b08ff693b73692c1189 to your computer and use it in GitHub Desktop.
orchestrator for composing tasks
const { series, parallel } = require('./orchestrator.js');
const buildSync = () => 'this was build synchronously';
const buildAsync = () => Promise.resolve('this could have been made asyncronously');
const tasks = series(
series(buildAsync, buildAsync),
series(buildAsync, buildSync),
parallel(buildAsync, buildSync, buildAsync),
);
tasks()
.then(results => console.log(results))
.catch(err => console.error(err));
const chalk = require('chalk');
function log(name, message) {
console.log([
chalk.bold(`[${chalk.green(name)}]`),
'-',
message,
].join(' '));
}
function createHandler(task) {
log(task.name, chalk.yellow('started'));
const promise = Promise.resolve(task());
return promise
.then((result) => {
log(task.name, chalk.green('done'));
return result;
});
}
const createParallel = (...tasks) => function parallel() {
return Promise.all(tasks.map(createHandler));
};
const createSeries = (...tasks) => {
const reducer = async (promiseChain, task) => {
const chainResult = await promiseChain;
const result = await createHandler(task);
return chainResult.concat(result);
};
const reducedTasks = tasks.reduce(reducer, Promise.resolve([]));
return function series() {
return reducedTasks;
};
};
module.exports = {
parallel: createParallel,
series: createSeries,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment