关于koa2:koa2洋葱模型的实现

49次阅读

共计 753 个字符,预计需要花费 2 分钟才能阅读完成。

koa2 的洋葱模型

  • 构造像洋葱

  • 申请过程穿梭洋葱, 有个来回

外围代码:

// 函数集 (相当于中间件汇合)
let arr = [(next) => {console.log('a1'); next(); console.log('a2'); },
  (next) => {console.log('b1'); next(); console.log('b2'); },
  (next) => {console.log('c1'); next(); console.log('c2'); },
];

// 用递归实现洋葱模型
let dispatch = (i) => {let fn = arr[i];
  if (typeof fn !== 'function') return
  let next = () => dispatch(i + 1);
  fn(next)
}
dispatch(0)

// 运行后果 ==> a1 > b1 > c1 > c2 > b2 > a1

包装一下, 用中间件形式调用.

let a = (next) => {console.log('a1'); next(); console.log('a2');
}
let b = (next) => {console.log('b1'); next(); console.log('b2');
}
let c = (next) => {console.log('c1'); next(); console.log('c2');
}

let compose = (arr) => {return (args) => {console.log(args);
    let dispatch = (index) => {let fn = arr[index];
      if (typeof fn !== 'function') return
      let next = () => dispatch(index + 1);
      fn(next);
    }
    dispatch(0)
  }
}
compose([a, b, c])('内部参数');

正文完
 0