1. 简化版

      1. function compose(middleware) {
      2. return function() {
      3. function dispatch(i) {
      4. let fn = middleware[i]
      5. if (!fn) return
      6. return fn(function next()) {
      7. return dispatch(i + 1)
      8. }
      9. }
      10. return dispatch(0)
      11. }
      12. }
    2. Promise 版

    1. function compose(middleware) {
    2. return function(ctx) {
    3. return dispatch(0)
    4. function dispatch(i) {
    5. let fn = middleware[i]
    6. if (!fn) return Promise.resolve()
    7. return Promise.resolve(
    8. fn(function next() {
    9. return dispatch(i + 1)
    10. })
    11. )
    12. }
    13. }
    14. }