美文网首页
模拟一个超级简单的中间件

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

作者: DoEmpty | 来源:发表于2021-04-20 14:07 被阅读0次
    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)
    

    相关文章

      网友评论

          本文标题:模拟一个超级简单的中间件

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