Koa 中间件机制学习

如题

// Koa 洋葱中间件机制核型代码
function compose(middleware) {
    return function (context, next) {
        let index = -1;
        return dispatch(0)
        function dispatch(i) {
            if (i <= index) {
                return Promise.reject(new Error('next() called multiple times'))
            }
            index = i
            let fn = middleware[i]
            if (i === middleware.length) {
                fn = next
            }
            if (!fn) {
                return Promise.resolve()
            }
            try {
                return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
            } catch (err) {
                return Promise.reject(err)
            }
        }
    }
}

function fn1(ctx, next) {
	console.log(1);
	next();
	console.log(2);
}
 
function fn2(ctx, next) {
	console.log(3);
	if(next) next();
	console.log(4);
}
 
function fn3(ctx, next) {
	console.log(5);
	if(next) next();
	console.log(6);
}

const middleware = [fn1, fn2, fn3]

console.log(compose(middleware)())
1
3
5
6
4
2
Promise { undefined }
原文地址:https://www.cnblogs.com/warrior/p/13540631.html