模拟实现koa中间件

100 阅读1分钟

分析

koa用use方法注册中间件,将中间件注册到数组中。请求进来后以先进后出的方式调用注册的函数(既以栈的方式调用注册的中间件)。

以栈的方式执行中间件,首先想到的肯定是递归。这样就是用递归的方式,执行数组中所有中间件函数

class Application {
    constructor() {
        this.middleware = [];
    }
    
    listen(...args) {
        const server = http.createServer(this.callback);
        return server.listen(...args);
    }
    
    // 注册中间件函数
    use(fn) {
        this.middleware.push(fn)
    }
    
    // 调用中间件函数
    callback() {
        // 使用递归的方式调用中间件,达到洋葱模型的效果。
        const dfs = function(index) {
           if (index >= this.middleware.length) return;
           const fn = this.middleware[index];
           fn(() => {
               dfs(index + 1)
           });
        }
        dfs(0)
    }
}