我们知道koa-compose
是koa
框架实现洋葱包裹型中间件的基础,通过一段简短的代码来理解它的使用方式及结果顺序
const compose = require('koa-compose');
const composes = [];
function use(fun) {
composes.push(fun);
}
use(async (ctx, next) => {
console.log('第一个中间件');
await next();
console.log('1->END');
});
use(async (ctx, next) => {
console.log('第二个中间件');
await next();
console.log('2->END');
});
use(async (ctx, next) => {
console.log('第三个中间件');
await next();
console.log('3->END');
});
const exec = compose(composes);
(async () => {
const ctx = {};
await exec(ctx, async () => {
console.log('END');
});
})();
结果如下