Skip to content

Instantly share code, notes, and snippets.

@Ariex
Created August 23, 2018 05:07
Show Gist options
  • Save Ariex/890b6e6db8c5024e84a722dd82fcad0e to your computer and use it in GitHub Desktop.
Save Ariex/890b6e6db8c5024e84a722dd82fcad0e to your computer and use it in GitHub Desktop.
demo of how middleware could be implemented with generator
class Application {
constructor() {
this.middlewares = [];
}
use(func) {
this.middlewares.push(func);
}
execute() {
let stack = [];
let idx = 0;
let m = this.middlewares[idx](this.middlewares[++idx]);
stack.splice(0, 0, m);
m = m.next();
while (typeof m.value !== "undefined") {
m = m.value(this.middlewares[++idx]);
stack.splice(0, 0, m);
m = m.next();
}
for (let s of stack) {
s.next();
}
}
}
var app = new Application();
var m1 = function*(next) {
var start = new Date;
console.log("m1 executing");
yield next;
var ms = new Date - start;
console.log(`m1 executed in ${ms}ms`);
};
app.use(m1);
var m2 = function*(next) {
var start = new Date;
console.log("m2 executing");
yield next;
var ms = new Date - start;
console.log(`m2 executed in ${ms}ms`);
};
app.use(m2);
var m3 = function*(next) {
var start = new Date;
console.log("m3 executing");
yield next;
var ms = new Date - start;
console.log(`m3 executed in ${ms}ms`);
};
app.use(m3);
var m4 = function*(next) {
var start = new Date;
console.log("m4 executing");
yield next;
var ms = new Date - start;
console.log(`m4 executed in ${ms}ms`);
};
app.use(m4);
var m5 = function*(next) {
var start = new Date;
console.log("m5 executing");
yield next;
var waitTill = new Date(new Date().getTime() + 3 * 1000);
while (waitTill > new Date()) {}
var ms = new Date - start;
console.log(`m5 executed in ${ms}ms`);
};
app.use(m5);
app.execute();
console.log("the end");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment