我們知道koa-compose
是koa
框架實(shí)現(xiàn)洋蔥包裹型中間件的基礎(chǔ),通過一段簡(jiǎn)短的代碼來理解它的使用方式及結(jié)果順序
const compose = require('koa-compose');
const composes = [];
function use(fun) {
composes.push(fun);
}
use(async (ctx, next) => {
console.log('第一個(gè)中間件');
await next();
console.log('1->END');
});
use(async (ctx, next) => {
console.log('第二個(gè)中間件');
await next();
console.log('2->END');
});
use(async (ctx, next) => {
console.log('第三個(gè)中間件');
await next();
console.log('3->END');
});
const exec = compose(composes);
(async () => {
const ctx = {};
await exec(ctx, async () => {
console.log('END');
});
})();
結(jié)果如下
執(zhí)行結(jié)果