模拟一个超级简单的中间件

class Midware {
    midwares = []
    use(fn) {
        this.midwares.push(fn)
    }

    start(initialCtx) {
        this.dispatch(0, initialCtx);
    }

    dispatch(index, ctx) {
        let current = this.midwares[index];
        if (index == this.midwares.length) {
            return Promise.resolve('所有执行完了');
        }
        return current(ctx, () => this.dispatch(index + 1, ctx))
    }
}

var ware = new Midware();
ware.use(async (ctx, next) => {
    ctx.age = 20;
    const result = await next()
    result.push('执行完了1')
    ctx.response = result;
})
ware.use(async (ctx, next) => {
    ctx.name = 'kerry';
    const result = await next()
    result.push('执行完了2')
    return result;
})
ware.use(async (ctx, next) => {
    ctx.money = 100000000000;
    const result = await next()
    return [result];
})
let context = {}
ware.start(context)
console.log(context)

你可能感兴趣的:(模拟一个超级简单的中间件)