Skip to content

Instantly share code, notes, and snippets.

@markbrown4
Last active November 24, 2017 09:51
Show Gist options
  • Save markbrown4/72344b728eeca74fc7d9e888cb7b2307 to your computer and use it in GitHub Desktop.
Save markbrown4/72344b728eeca74fc7d9e888cb7b2307 to your computer and use it in GitHub Desktop.
simple express-like middleware
class Middleware {
constructor () {
this.stack = []
}
use (fn) {
this.stack.push(fn)
}
go (next, remaining = this.stack.slice()) {
const fn = remaining.shift()
if (fn) {
fn(() => this.go(next, remaining))
} else {
next()
}
}
}
// Usage
const app = new Middleware()
app.use(function (next) {
console.log(1)
setTimeout(function () {
next()
}, 100)
})
app.use(function (next) {
console.log(2)
setTimeout(function () {
next()
}, 100)
})
app.go(function () {
console.log('done')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment