直接上代码
const http = require("http");
class Koa {
constructor() {
this.middleware = [];
}
use(fn) {
this.middleware.push(fn);
}
listen(port) {
let middleware = this.middleware;
let _this=this;
function serverFunc(req, res) {
let context = {
req,
res,
ctx:_this
};
let length = middleware.length;
run(0);
function run(n) {
if (n < length) {
const fn = middleware[n];
try {
return Promise.resolve(fn(context, run.bind(null, n + 1)));
} catch (err) {
return Promise.reject(err);
}
} else if (n === length) {
return Promise.resolve();
}
}
}
const app = http.createServer(serverFunc);
_this.app=app;
app.listen(port);
}
}
测试
const app = new Koa();
app.use(async (ctx, next) => {
console.log("one start");
await next();
console.log("one end");
});
app.use(async (ctx, next) => {
console.log("22222 start");
await next();
console.log("22222 end");
});
app.use(async (ctx, next) => {
console.log("33333 start");
await next();
console.log("33333 end");
});
app.listen(19191);
运行,在浏览器中访问http://localhost:19191/,运行结果 如下
one start
22222 start
33333 start
33333 end
22222 end
one end
网友评论