image.png
    三种注册方式: tap 同步注册 call, tapAsync 异步注册 callAsync, tapPromise 注册个promise, then

    异步触发一定有回调 cb

    1. class SyncHook {
    2. constructor(args) {
    3. this.tasks = []
    4. }
    5. call(...args) {
    6. // this.tasks.forEach(task => task(...args))
    7. // let ret // 当前函数的返回值
    8. // let index = 0 // 当前执行的函数索引
    9. // do {
    10. // ret = this.tasks[index++](...args)
    11. // }while(ret == undefined && index < this.tasks.length)
    12. let [first, ...others] = this.tasks
    13. let ret = first(...args)
    14. others.reduce((a, b) => {
    15. return b(a) // return 的就是上一个
    16. }, ret)
    17. }
    18. tapPromise(...args) {
    19. let [first, ...others] = this.tasks
    20. return others.reduce((p, n) => {
    21. return p.then(() => n(...args))
    22. }, first(...args))
    23. }
    24. tap(name, task) {
    25. this.tasks.push(task)
    26. }
    27. }