JavaScript实现类koa中间件方法

812 阅读1分钟

前言

在前端各种异步方法当道的今天,各种异步方法让人求生不得,求死不能。因此,寻求一个好的解决方案,还是能让人陶醉的。其中koa和express的中间件,给了我思路。下面是实现方法。

实现方式

class Iterator {
    constructor () {
        this.middlewares = []
    }

    use (module) {
        Array.isArray(module) ? module.map(item => this.use(item)) : this.middlewares.push(module)
        return this
    }

    async run (ctx) {
        function createNext (middleware, oldNext) {
            return async () => {
                await middleware(ctx, oldNext)
            }
        }

        let len = this.middlewares.length
        let next = async () => {
            return Promise.resolve()
        }

        for (let i = len - 1; i >= 0; i--) {
            let currentMiddleware = this.middlewares[i]
            next = createNext(currentMiddleware, next)
        }
        await next()
    }
}

使用方法

let app = new Iterator();
app.use(async (ctx,next)=>{
    console.log("start:a");
    await next();
    console.log("end:a");
});
 
app.use(async (ctx,next)=>{
    console.log("start:b");
    await next();
    console.log("end:b");
});
app.run();