Created
August 21, 2017 15:56
-
-
Save Lucifier129/b0ac35be888559b277c6849bc1b5b554 to your computer and use it in GitHub Desktop.
an implementation of middleware composing
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
| class App { | |
| constructor() { | |
| this.middlewares = [] | |
| } | |
| use(...middlewares) { | |
| this.middlewares.push(...middlewares) | |
| } | |
| next(index = 0) { | |
| let middleware = this.middlewares[index] | |
| return middleware ? middleware(() => this.next(index + 1)) : null | |
| } | |
| then(resolve) { | |
| resolve(this.next(0)) | |
| } | |
| } | |
| var app = new App() | |
| app.use(async next => { | |
| console.log(1) | |
| await next() | |
| console.log(2) | |
| }) | |
| app.use(async next => { | |
| console.log(3) | |
| await next() | |
| console.log(4) | |
| }) | |
| app.use(async next => { | |
| console.log(5) | |
| await next() | |
| console.log(6) | |
| }) | |
| app.use(async next => { | |
| console.log(7) | |
| await next() | |
| console.log(8) | |
| }) | |
| Promise.resolve(app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment