onion洋葱模型

javascript 复制代码
const log = console.log;
function m1(next) { log(1); next(); log(2); }
function m2(next) { log(3); next(); log(4); }
function m3(next) { log(5); next(); log(6); }

function end() { log('end'); }
function m3_end() { m3(end); }
function m2_end() { m2(m3_end); }
m1(m2_end);
// 打印顺序 1 3 5 end 6 4 2

利用高阶函数

fn => compose();

高阶函数:

  1. 入口参数是函数;
  2. 返回函数;
  3. 两者皆备;
javascript 复制代码
const log = console.log;
function m1(next) { log(1); next(); log(2); }
function m2(next) { log(3); next(); log(4); }
function m3(next) { log(5); next(); log(6); }

let ms = [];
use(m1); use(m2); use(m3);
function use(mx) {
  ms.push(mx);
}

let index = 0;
function compose(index = 0) {
  if (index === ms.length) {
    return () => { log('end') };
  }
  return () => {
    ms[index](compose(index + 1));
  };
}

let fn = compose();
fn();
相关推荐
ZzMemory2 分钟前
深入理解JS(八):事件循环,单线程的“一心多用”
前端·javascript·面试
FogLetter4 分钟前
玩转Canvas:从静态图像到动态动画的奇妙之旅
前端·canvas
llq_3505 分钟前
解决 Linux 部署中的文件大小写问题
前端
我想说一句6 分钟前
bubu智聘App亮点详解(2) Coze工作流接入
前端·前端框架·trae
llq_3508 分钟前
配置 Git 使其大小写敏感:解决文件名大小写变更的识别问题
前端
钢铁男儿13 分钟前
C# 异步编程(GUI程序中的异步操作)
开发语言·c#
猫葫芦15 分钟前
微信【跳转】相关API详细整理,含注意事项
前端
蓝色笙箫本尊19 分钟前
truffle安装
前端
默默地离开20 分钟前
Tailwind CSS 4,把样式这事儿交给“类名”就好
前端·css
子洋20 分钟前
OrbStack 安装 Ubuntu 并开启 SSH 与 Root 登陆
linux·前端·ubuntu