# 四.SyncLoopHook

前言

同步循环执行全部直到没结果,队列顺序

  • SyncLoopHook 的特点是不停的循环执行回调函数,直到函数结果等于 undefined
  • 要注意的是每次循环都是从头开始循环的

# 1.使用方式

let { SyncLoopHook } = require("tapable")

class Lesson {
  constructor() {
    this.hooks = { arch: new SyncLoopHook(["name"]) }
  }
  tap() {
    //注册监听函数
    this.hooks.arch.tap("node", (name) => {
      console.log("node", name)
      return ++this.index === 3 ? undefined : "继续"
    })
    this.hooks.arch.tap("react", (name) => {
      console.log("react", name)
    })
  }
  statr() {
    this.hooks.arch.call("123")
  }
}
let l = new Lesson()
l.tap() //注册这两个事件
l.statr() //启动钩子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

运行得到:

node 123
node 123
node 123
...
1
2
3
4

# 2.原理实现

class SyncWaterfallHook {
  //同步方法
  constructor(args) {
    //args => ['name']
    this.tasks = []
  }
  tap(name, task) {
    this.tasks.push(task)
  }
  call(...args) {
    this.tasks.forEach((task) => {
      let ret
      do {
        ret = task(...args)
      } while (ret !== undefined)
    })
  }
}
let hook = new SyncWaterfallHook(["name"])
let total = 0
hook.tap("node", function (name) {
  console.log("node", name)
  return ++total == 3 ? undefined : "continue"
})
hook.tap("react", function (name) {
  console.log("react", name)
})
hook.tap("webpack", function (name) {
  console.log("webpack", name)
})
hook.call("123")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31