koa2洋葱模型的实现
首页 专栏 javascript 文章详情
0
头图

koa2洋葱模型的实现

ttwtdxp 发布于 5 月 14 日

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

koa2 javascript 递归 node.js 模型
阅读 59 更新于 5 月 14 日
收藏
分享
本作品系原创, 采用《署名-非商业性使用-禁止演绎 4.0 国际》许可协议
avatar
ttwtdxp

前端

1 声望
0 粉丝
关注作者
0 条评论
得票数 最新
提交评论
你知道吗?

注册登录
avatar
ttwtdxp

前端

1 声望
0 粉丝
关注作者
宣传栏
目录

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