前言

Koa.js 最为人所知的是基于 洋葱模型 的HTTP中间件处理流程。
在此,洋葱模式可以拆解成一下几个元素。

  • 生命周期
  • 中间件
  • 中间件在生命周期中

    • 前置操作
    • 等待其他中间件操作
    • 后置操作

      中间件流程处理

  • 举个代码例子

    1. let context = {
    2. data: []
    3. };
    4. async function middleware1(ctx, next) {
    5. console.log('action 001');
    6. ctx.data.push(1);
    7. await next();
    8. console.log('action 006');
    9. ctx.data.push(6);
    10. }
    11. async function middleware2(ctx, next) {
    12. console.log('action 002');
    13. ctx.data.push(2);
    14. await next();
    15. console.log('action 005');
    16. ctx.data.push(5);
    17. }
    18. async function middleware3(ctx, next) {
    19. console.log('action 003');
    20. ctx.data.push(3);
    21. await next();
    22. console.log('action 004');
    23. ctx.data.push(4);
    24. }
    25. Promise.resolve(middleware1(context, async() => {
    26. return Promise.resolve(middleware2(context, async() => {
    27. return Promise.resolve(middleware3(context, async() => {
    28. return Promise.resolve();
    29. }));
    30. }));
    31. }))
    32. .then(() => {
    33. console.log('end');
    34. console.log('context = ', context);
    35. });
    36. // 结果显示
    37. // "action 001"
    38. // "action 002"
    39. // "action 003"
    40. // "action 004"
    41. // "action 005"
    42. // "action 006"
    43. // "end"
    44. // "context = { data: [1, 2, 3, 4, 5, 6]}"
  • 源码元素解析

    • 生命周期就是 Promise.resolve 的嵌套
    • 中间件就是 middleware1middleware2middleware3
    • 中间件在生命周期中,就是Promise.resolve(middleware)嵌套中执行中间件
      • middleware1 前置操作 action 001
      • 等待嵌套的middleware2
        • middleware2 前置操作 action 002
        • 等待嵌套的middleware3
          • middleware3 前置操作 action 003
          • middleware3 后置操作 action 004
        • middleware2 后置操作 action 005
      • middleware1 后置操作 action 006
        1. +----------------------------------------------------------------------------------+
        2. | |
        3. | middleware 1 |
        4. | |
        5. | +-----------------------------------------------------------+ |
        6. | | | |
        7. | | middleware 2 | |
        8. | | | |
        9. | | +---------------------------------+ | |
        10. | | | | | |
        11. | action | action | middleware 3 | action | action |
        12. | 001 | 002 | | 005 | 006 |
        13. | | | action action | | |
        14. | | | 003 004 | | |
        15. | | | | | |
        16. +---------------------------------------------------------------------------------------------------->
        17. | | | | | |
        18. | | | | | |
        19. | | +---------------------------------+ | |
        20. | +-----------------------------------------------------------+ |
        21. +----------------------------------------------------------------------------------+