js 鏈式呼叫

howhy發表於2024-04-29
function arrany(name) {
  let tasks = []
  tasks.push(() => {
    console.log(name)
  })
  function wait(duration) {
    tasks.push(() => new Promise(resolve => {
      setTimeout(resolve, duration)
    }))
    return this
  }
  function execute() {
    for (let task of tasks) {
      task()
    }
    return this
  }
  function dosomething(aa) {
    tasks.push(() => {
      console.log('do ' + aa)
    })
    return this
  }
  function waitFirst(dur) {
    tasks.unshift(() => new Promise(resolve => {
      console.log('first')
      setTimeout(resolve, dur)
    }))
    return this
  }
  return {
    wait,
    do: dosomething,
    waitFirst,
    execute
  }
}

function add(a, b) {
  console.log(a + b)
}

ret = arrany('test').wait(6000).do('111111').waitFirst(2000)

相關文章