头图

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])('外部参数');


ttwtdxp
11 声望0 粉丝

前端