Created
January 12, 2024 12:39
-
-
Save zhoufenfens/fdf38933e8a179e4f37d8e97e2686e94 to your computer and use it in GitHub Desktop.
koa中间件
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
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