Node.js 中间件原理

const app = {
  middleware: [],

  callback (ctx) {
    console.log(ctx)
  },

  use (fn) {
    this.middleware.push(fn)
  },

  go (ctx) {
    this.middleware.reduceRight((next, fn, i) => {
      return () => {
        console.log('next: ', next)
        console.log('fn: ', fn)
        fn(ctx, next)
      }
    }, this.callback.bind(this, ctx))()
  }
}

app.use((ctx, next) => {
  ctx.name = 'Lucy'
  next()
})

app.use((ctx, next) => {
  ctx.age = 12
  next()
})

app.use((ctx, next) => {
  console.log(`${ctx.name} is ${ctx.age} years old.`)
  next()
})

app.go({})

上面代码的执行结果是

next:  () => {
  console.log('next: ', next)
  console.log('fn: ', fn)
  fn(ctx, next)
}
fn:  (ctx, next) => {
  ctx.name = 'Lucy'
  next()
}
next:  () => {
  console.log('next: ', next)
  console.log('fn: ', fn)
  fn(ctx, next)
}
fn:  (ctx, next) => {
  ctx.age = 12
  next()
}
next:  ƒ callback(ctx) {
  console.log(ctx)
}
fn:  (ctx, next) => {
  console.log(`${ctx.name} is ${ctx.age} years old.`)
  next()
}
Lucy is 12 years old.
{name: "Lucy", age: 12}

有没有大佬能解释一下执行结果为啥是这个

阅读 2.1k
1 个回答

可以看一下reduceRight
第一个参数是上次调用回调的返回值也就是next
第二个参数是当前元素值
reduceRight从右往左执行,执行完毕将最后一步也就是数组的第一位的回调返回并将第二位的回调以参数next的形式传入,然后以此类推,最后调用callbakc方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题