Open TopGrd opened 5 years ago
function compose(middlewares) {
return function middleware(ctx, next) {
let index = -1;
function dispatch(n) {
if (n <= index) return Promise.reject(new Error('multitime call midware'));
index = n;
let fn = middlewares[n];
if (n === middlewares.length) fn = next;
if (!fn) return Promise.resolve();
try {
return Promise.resolve(fn(ctx, () => dispatch(n + 1)));
} catch (error) {
return Promise.reject(error);
}
}
return dispatch(0);
};
}
简单模拟
function express() {
const app = { middlewares: [] };
app.use = function use(middleware) {
app.middlewares.push(middleware);
};
const req = {};
const res = {};
let i = 0;
function next() {
if (i === app.middlewares.length) {
return;
}
const fn = app.middlewares[i++];
fn.call(app, req, res, next);
}
app.listen = function listen(port, callback) {
callback(port);
next();
};
return app;
}
const app = express();
app.use((req, res, next) => {
console.log('ss1');
req.body = { name: 'as' };
next();
console.log('ss2');
});
app.use((req, res, next) => {
console.log(req);
console.log('ss4');
next();
console.log('ss5');
});
app.listen(3000, (port) => {
console.log('listen start', port);
});
koa/koa-vs-express.md at master · koajs/koa
Philosophically, Koa aims to "fix and replace node", whereas Express "augments node".Koa uses promises and async functions to rid apps of callback hell and…
August 30, 2019 at 04:32PM
via Instapaper https://ift.tt/1mz3cgb