Skip to content

Instantly share code, notes, and snippets.

@oxUnd
Created June 22, 2017 03:24
Show Gist options
  • Save oxUnd/f2f6c87890677b5488df1776a8374b0f to your computer and use it in GitHub Desktop.
Save oxUnd/f2f6c87890677b5488df1776a8374b0f to your computer and use it in GitHub Desktop.
function noop() {
}
class Dispatcher {
constructor() {
this.ctx = {
tasks: [],
done: noop,
context: {}
};
}
use(task) {
this.ctx.tasks.push(task);
return this;
}
done(done) {
this.ctx.done = done;
return this;
}
run() {
var ctx = this.ctx;
return dispatch(0);
function dispatch(idx) {
let task = ctx.tasks[idx];
if (ctx.tasks.length == idx) task = ctx.done;
function next() {
idx++;
dispatch(idx);
}
if (!task) {
return;
}
return task(ctx.context, next);
}
}
}
module.exports = new Dispatcher();
module.noop = noop;
const dispatcher = require('./dispacher.js');
dispatcher.use(function (ctx, next) {
console.log('A');
setTimeout(function () {
console.log('1s A');
next();
}, 1000);
});
dispatcher.use(function (ctx, next) {
console.log('B');
next();
});
dispatcher.done(function () {
console.log('done');
});
dispatcher.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment