Skip to content

Instantly share code, notes, and snippets.

@Ariex
Last active August 23, 2018 05:28
Show Gist options
  • Save Ariex/f42acf8ebc9c84573003eb382ba64cbf to your computer and use it in GitHub Desktop.
Save Ariex/f42acf8ebc9c84573003eb382ba64cbf to your computer and use it in GitHub Desktop.
demo of how middleware could be implemented with async/await
(async () => {
class Application {
constructor() {
this.middlewares = [];
}
use(func) {
this.middlewares.splice(0, 0, func);
}
async execute() {
await this.middlewares.reduce((a, b) => {
return async () => b(a);
}, async () => { })();
}
}
var app = new Application();
var m1 = async function (next) {
var start = new Date;
console.log("m1 executing");
await next();
var ms = new Date - start;
console.log(`m1 executed in ${ms}ms`);
}
app.use(m1);
var m2 = async function (next) {
var start = new Date;
console.log("m2 executing");
await next();
var ms = new Date - start;
console.log(`m2 executed in ${ms}ms`);
};
app.use(m2);
var m3 = async function (next) {
var start = new Date;
console.log("m3 executing");
await next();
var ms = new Date - start;
console.log(`m3 executed in ${ms}ms`);
};
app.use(m3);
var m4 = async function (next) {
var start = new Date;
console.log("m4 executing");
await next();
var ms = new Date - start;
console.log(`m4 executed in ${ms}ms`);
};
app.use(m4);
var m5 = async function (next) {
var start = new Date;
console.log("m5 executing");
await 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);
await app.execute();
console.log("the end");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment