Skip to content

Instantly share code, notes, and snippets.

@zhoufenfens
Created January 12, 2024 12:39
Show Gist options
  • Save zhoufenfens/fdf38933e8a179e4f37d8e97e2686e94 to your computer and use it in GitHub Desktop.
Save zhoufenfens/fdf38933e8a179e4f37d8e97e2686e94 to your computer and use it in GitHub Desktop.
koa中间件
const middleware = []
let mw1 = async function (ctx, next) {
console.log("next前,第一个中间件", new Date().getTime())
await next()
console.log("next后,第一个中间件", new Date().getTime())
}
let mw2 = async function (ctx, next) {
console.log("next前,第二个中间件", new Date().getTime())
await next()
console.log("next后,第二个中间件", new Date().getTime())
}
let mw3 = async function (ctx, next) {
console.log("第三个中间件,没有next了", new Date().getTime())
}
function use(mw) {
middleware.push(mw)
}
use(mw1)
use(mw2)
use(mw3)
let fn = function (ctx) {
return dispatch(0)
function dispatch(i) {
let currentMW = middleware[i]
if (!currentMW) {
return Promise.reject('没有中间件')
}
return currentMW(ctx, dispatch.bind(null, i+1))
}
}
fn()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment