Last active
November 24, 2017 09:51
-
-
Save markbrown4/72344b728eeca74fc7d9e888cb7b2307 to your computer and use it in GitHub Desktop.
simple express-like middleware
This file contains 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 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