-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Node框架那些事儿 #254
Comments
express和koa的区别1.中间件实现方式不同 express是callback方式,会有callback hell问题;koa为洋葱模型,基于promise和async实现 egg和koa的区别1.egg基于koa实现 |
koa洋葱模型中间件实现原理const middleware = []
let mw1 = async function (ctx, next) {
console.log("next前,第一个中间件")
next()
console.log("next后,第一个中间件")
}
let mw2 = async function (ctx, next) {
console.log("next前,第二个中间件")
next()
console.log("next后,第二个中间件")
}
let mw3 = async function (ctx, next) {
console.log("第三个中间件,没有next了")
}
function use(mw) {
middleware.push(mw);
}
function compose(middleware) {
return (ctx, next) => {
return dispatch(0);
function dispatch(i) {
const fn = middleware[i];
if (!fn) return;
return fn(ctx, dispatch.bind(null, i+1));
}
}
}
use(mw1);
use(mw2);
use(mw3);
const fn = compose(middleware);
fn(); async promise版 const middleware = []
let mw1 = async function (ctx, next) {
console.log("next前,第一个中间件")
await next()
console.log("next后,第一个中间件")
}
let mw2 = async function (ctx, next) {
console.log("next前,第二个中间件")
await next()
console.log("next后,第二个中间件")
}
let mw3 = async function (ctx, next) {
console.log("第三个中间件,没有next了")
}
function use(mw) {
middleware.push(mw);
}
function compose(middleware) {
return (ctx, next) => {
return dispatch(0);
function dispatch(i) {
const fn = middleware[i];
if (!fn) return Promise.resolve();
return Promise.resolve(fn(ctx, dispatch.bind(null, i+1)));
}
}
}
use(mw1);
use(mw2);
use(mw3);
const fn = compose(middleware);
fn();
// next前,第一个中间件
// next前,第二个中间件
// 第三个中间件,没有next了
// next后,第二个中间件
// next后,第一个中间件 Koa中间件koa-compose解决了什么问题?解决了callback回调地狱问题以及请求执行完后再执行响应的问题。 什么时候为返回执行response的时机?i+1不断累加,指向了middleware[middleware.length],即超出数据边界时,当fn为空时,开始执行返回逻辑。 if(!fn) return; 当前中间件执行是如何获取下一个中间件next的?通过bind生成一个全新的middle。 dispatch.bind(null, i+1)
``` |
nodejs框架,express,koa,egg
The text was updated successfully, but these errors were encountered: