JS手写实现洋葱圈模型

本文通过实例解析了JavaScript中的洋葱圈模型,展示了如何在TaskPro类中使用中间件,以及异步调用next()对执行顺序的影响。当执行中间件时,它们按照添加的顺序依次执行,直到所有任务完成后重置状态。
摘要由CSDN通过智能技术生成

解释洋葱圈模型:

当我们执行第一个中间件时,首先输出1,然后调用next(),那么此时它会等第二个中间件执行完毕才会继续执行第一个中间件。然后执行第二个中间件,输出3,调用next(),执行第三中间件,输出5.此时第三个中间件执行完毕,返回到第二个中间件,输出4,然后返回到第一个中间件。

class TaskPro {
  constructor() {
    this._TaskList = []
    this._isRunning = false
    this._currentIndex = 0
    // next 函数,要支持异步
    this._next = async () => {
      this._currentIndex++
      await this._runTask()
    }
  }

  // 添加任务函数
  addTask(task) {
    this._TaskList.push(task)
  }

  // run 函数
  run() {
    if(this._isRunning || !this._TaskList.length) return
    this._isRunning = true
    this._runTask()
  }

  // 执行任务函数,要支持异步
  async _runTask() {
    // 当前索引 >= 任务列表长度,表示已全部执行完
    if(this._currentIndex >= this._TaskList.length){
      this._reset()
      return
    }
    const i = this._currentIndex
    const taskItem = this._TaskList[this._currentIndex]
    await taskItem(this._next)
    const j = this._currentIndex
    // 如果执行前的下标和执行后的下标相同,表示没有调用 next() 那么自行调用
    if(i === j) {
      this._next()
    }
  } 
  
  // 重置函数
  _reset() {
    this._TaskList = []
    this._currentIndex = 0
    this._isRunning = false
  }
}

const taskPro = new TaskPro()
taskPro.addTask(async (next) => {
  console.log(1, '打印测试');
  await next()
  console.log('1-1', '打印测试');
  
})

taskPro.addTask(() => {
  console.log(2, '打印测试');
})

taskPro.addTask(() => {
  console.log(3, '打印测试');
})

taskPro.run()
taskPro.run()

// 最终输出结果
// 1 打印测试
// 2 打印测试
// 3 打印测试
// 1-1 打印测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@前端小菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值