Skip to content

Instantly share code, notes, and snippets.

@sweet-zone
Created May 31, 2017 06:18
Show Gist options
  • Save sweet-zone/a620c3cb8f4e0889c8f42f4066a6952f to your computer and use it in GitHub Desktop.
Save sweet-zone/a620c3cb8f4e0889c8f42f4066a6952f to your computer and use it in GitHub Desktop.
中间件
const app = {
callback (ctx) {
console.log(ctx)
},
use (fn) {
app.middleware = app.middleware || []
app.middleware.push(fn)
},
go (ctx) {
app.middleware = app.middleware || []
var func = app.middleware.reverse().reduce(function(preMiddle, nextMiddle) {
return function() {
return nextMiddle(ctx, preMiddle)
}
}, function() {
return app.callback(ctx)
})
func()
}
}
app.use((ctx, next) => {
ctx.name = 'Lucy'
next()
})
app.use((ctx, next) => {
ctx.age = 12
next()
})
app.use((ctx, next) => {
console.log(`${ctx.name} is ${ctx.age} years old.`) // => Lucy is 12 years old.
next()
})
app.go({})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment