在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Node.js 中間件原理

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({})

上面代碼的執(zhí)行結(jié)果是

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}

有沒有大佬能解釋一下執(zhí)行結(jié)果為啥是這個

回答
編輯回答
孤慣

可以看一下reduceRight
第一個參數(shù)是上次調(diào)用回調(diào)的返回值也就是next
第二個參數(shù)是當(dāng)前元素值
reduceRight從右往左執(zhí)行,執(zhí)行完畢將最后一步也就是數(shù)組的第一位的回調(diào)返回并將第二位的回調(diào)以參數(shù)next的形式傳入,然后以此類推,最后調(diào)用callbakc方法

2017年3月9日 13:35