Created
June 22, 2017 03:24
-
-
Save oxUnd/f2f6c87890677b5488df1776a8374b0f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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