koa洋葱模型即是注册的中间件采取先进后出的运行策略。
问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var app = { middlewares: [] };
app.use = function(fn) { app.middlewares.push(fn); };
app.compose = function() { function dispatch(index) { if (index === app.middlewares.length) return Promise.resolve();
const middleware = app.middlewares[index]; return Promise.resolve(middleware(() => dispatch(index + 1))); }
dispatch(0); };
|
留言
欢迎交流想法。留言会通过 GitHub Issues 保存,首次使用需要登录 GitHub。