koa洋葱模型即是注册的中间件采取先进后出的运行策略。
问题
app.use(async next => {
console.log(1);
await next();
console.log(2);
});
app.use(async next => {
console.log(3);
await next();
console.log(4);
});
// 异步函数
function fn() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("hello");
}, 3000);
});
}
app.use(async next => {
console.log(5);
let res = await fn(); // 调用异步函数
console.log(res)
await next();
console.log(6);
});
app.compose();
实现use与compose方法,预期输出如下结果
1
3
5
hello
6
4
2
方法实现
var app = {
middlewares: []
};
// 创建 use 方法
app.use = function(fn) {
app.middlewares.push(fn);
};
app.compose = function() {
// 递归函数
function dispatch(index) {
// 如果所有中间件都执行完跳出
if (index === app.middlewares.length) return Promise.resolve();
// 取出第 index 个中间件并执行
const middleware = app.middlewares[index];
// 核心在这一行
return Promise.resolve(middleware(() => dispatch(index + 1)));
}
// 取出第一个中间件函数执行
dispatch(0);
};