手写洋葱模型

301 阅读1分钟
const middlewares = [];
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了")
}

const use = (fn) => {
    middlewares.push(fn);
}

use(mw1);
use(mw2);
use(mw3);

const compose = (middlewares) => {
    return (ctx, next) => {
        return dispatch(0);
        function dispatch(i) {
            const fn = middlewares[i];
            if(!fn) return null;
            // 重点:next就是执行dispatch(i)
            return fn(ctx, dispatch.bind(null, i+1));
        }
    }
}
const fn = compose(middlewares);
fn();