Skip to content

Instantly share code, notes, and snippets.

@Lucifier129
Created August 21, 2017 15:56
Show Gist options
  • Select an option

  • Save Lucifier129/b0ac35be888559b277c6849bc1b5b554 to your computer and use it in GitHub Desktop.

Select an option

Save Lucifier129/b0ac35be888559b277c6849bc1b5b554 to your computer and use it in GitHub Desktop.
an implementation of middleware composing
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