带异步的链式调用实现

578 阅读1分钟

队列

// 链式调用:函数都 return this
// 链式调用时(同步过程),会将每个任务(函数)放到 队列中(tasks)
// 使用 start 函数异步开始执行第一个任务( next 函数第一次调用) 每一个任务执行完就 再调用 next 函数,next 会取出下一个任务出来执行
class Chaos {
  constructor() {
    this.tasks = []
    const fn = () => {
      console.log('chain start')
      this.next()
    }
    this.tasks.push(fn)
  }
  start() {
    // 启动调用
    Promise.resolve().then(() => {
      this.next()
    })
    return this
  }
  next() {
    const fn = this.tasks.shift();
    fn && fn()
  }
  sleep(n) {
    const fn = () => {
      console.log('sleep start')
      setTimeout(() => {
        console.log('sleep end')
        this.next()
      }, n * 1000)
    }
    this.tasks.push(fn)
    return this
  }
  work() {
    const fn = () => {
      console.log('work')
      this.next()
    }
    this.tasks.push(fn)
    return this
  }
  eat() {
    const fn = () => {
      console.log('eat')
      this.next()
    }
    this.tasks.push(fn)
    return this
  }
}
const chain = () => {
  return new Chaos().start()
}
chain().eat().sleep(5).work().eat().work().sleep(10)

Promise

class Chains {
  task = Promise.resolve()
  eat() {
    this.task = this.task.then(() => {
      console.log('eat')
    })
    return this
  }
  work() {
    this.task = this.task.then(() => {
      console.log('work')
    })
    return this
  }
  sleep(n) {
    this.task = this.task.then(() => {
      console.log('sleep start')
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log('sleep end')
          resolve()
        }, n * 1000)
      })
    })
    return this
  }
}
const chain = () => new Chains()
chain().eat().sleep(5).work().eat().work().sleep(10)