美文网首页
Koa 洋葱模型简单实现

Koa 洋葱模型简单实现

作者: 立立亭亭 | 来源:发表于2020-09-10 11:05 被阅读0次

    直接上代码

    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
    

    相关文章

      网友评论

          本文标题:Koa 洋葱模型简单实现

          本文链接:https://www.haomeiwen.com/subject/nfnwrktx.html