zoukankan      html  css  js  c++  java
  • 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 }
    
  • 相关阅读:
    监控体系(二)
    piwik安装部署
    smokeping安装部署
    监控体系(一)
    学习zabbix(九)
    学习zabbix(八)
    学习zabbix(七)
    学习zabbix(六)
    数据结构之树形结构
    数据结构之线性结构
  • 原文地址:https://www.cnblogs.com/warrior/p/13540631.html
Copyright © 2011-2022 走看看