洋葱模型

47 阅读1分钟

实现需求:

  taskPro.addTask(async(next) => {
      console.log(0)
      await next()
      console.log('end')
  })
  taskPro.addTask(() => {
      console.log(2)
  })
  taskPro.addTask(() => {
      console.log(3)
  })
    taskPro.run()

需要输出0 2 3 end

分析:添加形成一个列表,列表按照顺序执行,遇到next的时候直接调用下一个函数。主要是next,next 的作用是执行下一个函数,并且next入参可以不存在,不存在的时候需要手动调用下一个函数 实现如下,可直接运行

<!DOCTYPE html>
<html>
  <body>
    <script>
      class TaskPro {
        constructor () {
          this.list = []
          this.index = 0
          this.isRunning = false
          this.next = async() => {
            if (this.index + 1 >= this.list.length) return
            this.index++
            await this.runTask()
          }
        }
        addTask (fn) {
          this.list.push(fn)
        }
        async runTask() {
          if (this.index >= this.list.length) {
            this.index = 0
            this.list = []
            this.isRunning = false
            return
          }
          const i = this.index
          const fn = this.list[this.index]
          await fn(this.next)
          const j = this.index
          if (i === j) { // 没有传参数的时候手动调用next
            await this.next()
          }
        }
        async run() {
          if (this.isRunning){
            return
          }
          this.isRunning = true
          await this.runTask()
        }
      }
      const taskPro = new TaskPro()
      taskPro.addTask(async(next) => {
          console.log(0)
          await next()
          console.log('end')
        })
      taskPro.addTask(() => {
        console.log(2)
      })
      taskPro.addTask(() => {
        console.log(3)
      })
      taskPro.run()
    </script>
  </body>
</html>