实现链式调用

实现链式调用

arrange(‘William’).wait(5).do(‘commit’).wait(5).do(‘push’).execute();

调用 wait 进行等待
调用 do 则执行对应的指令
调用 execute 则执行所有的该 arrange 指令,不调用则不执行

class Arrange {
  value: any
  queue: Array<() => Promise<any>> = []

  constructor(value: any) {
    this.value = value
  }

  wait(delay: number): Arrange {
    // push 一个函数,返回 Promise 的一个定时器,使用 Promise 可以保证执行顺序
    this.queue.push(() => new Promise(resolve => {
      setTimeout(() => {
        resolve('delay ' + delay)
      }, delay)
    }))
    
    // 返回实例对象
    return this
  }

  do(action: string): Arrange {
    // push 一个函数,返回 Promise 的值
    this.queue.push(() => {
      return new Promise(resolve => resolve(action))
    })
    // 返回实例对象
    return this
  }

  /**
   * 同步调用,利用 async-await 进行等待
   */
  async execute() {
    for (const fn of this.queue) {
      const res = await fn()
      console.log(res)
    }
    console.log(this.value)
  }

  /**
   * 异步调用,利用 Promise.then 进行递归等待,保证顺序执行
   */
  syncExecute() {
    if (this.queue.length) {
      // 推出数组第一个开始执行
      this.queue.shift()!()
        .then(res => {
          console.log(res)
          // 递归执行下一个指令
          this.syncExecute()
        })
    } else {
      console.log(this.value)
    }
  }
}

function arrange(value: any): Arrange {
  return new Arrange(value)
}

arrange('William')
  .wait(1000)
  .do('commit')
  .do('push2')
  .wait(1000)
  .do('push3')
  .wait(1000)
  .do('push4')
  .wait(1000)
  .do('push5')
  .execute()
  // .syncExecute()
  
// 结果
// delay 1000
// commit
// push2
// delay 1000
// push3
// delay 1000
// push4
// delay 1000
// push5
// William
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值