实现 arrange 函数 arrange('William').wait(5).do('commit').execute()

实现 arrange 函数

arrange('William').execute();
// > William is notified

arrange('William').do('commit').execute();
// > William is notified
// > Start to commit

arrange('William').wait(5).do('commit').execute();
// > William is notified
// 等待5秒
// > Start to commit

arrange('William').waitFirst(5).do('push').execute();
// 等待5秒
// > William is notified
// > Start to push

解答

function arrange(str) {
  return new Arrange(str)
}

class Arrange {
  constructor(str){
    this.str = str
    this.tasks = [] // 核心,使用队列(数组)来存储要执行的函数

    this.tasks.push(() => console.log(`${this.str} is notified`))
  }
  
  async execute() {
    for(const t of this.tasks) {
      await t() // 执行队列中的函数
    }
  }

  do(action) {
    this.tasks.push(() => {
      console.log(`start to ${action}`);
    })
    return this
  }

  wait(time) {
    this.tasks.push(() => new Promise((resolve) => {
      console.log(`等待 ${time} s`);
      setTimeout(() => resolve(), time * 1000)
    }))

    return this
  }

  waitFirst(time) {
    this.tasks.unshift(() => new Promise((resolve) => {
      console.log(`等待 ${time} s`);
      setTimeout(() => resolve(), time * 1000)
    }))

    return this
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。