onion洋葱模型

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. 两者皆备;
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();
上一篇:深入理解Python多进程:从基础到实战-第三章:进程池与异步编程


下一篇:微服务使用SockJs+Stomp实现Websocket 前后端实例 | Vuex形式断开重连、跨域等等问题踩坑(二)