likes
comments
collection
share

koa2洋葱模型的实现

作者站长头像
站长
· 阅读数 15

koa2的洋葱模型

  • 结构像洋葱koa2洋葱模型的实现

  • 请求过程穿越洋葱,有个来回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])('外部参数');

转载自:https://segmentfault.com/a/1190000040003999
评论
请登录