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