Skip to content

链式调用和延迟执行

Code

ts
// 实现
arrange('William').wait(5).do('commit').waitFirst(3).execute();
// 等待3s
// > William is notified
// 等待5s
// > Start to commit

解析

ts
function arrange(name) {
  const tasks = [];

  tasks.push(() => `${name}  is notified`);

  function wait(time) {
    tasks.push(
      () => new Promise((resolve) => setTimeout(resolve, time * 1000))
    );
    return this;
  }

  function doSomething(action) {
    tasks.push(() => `Start to ${action}`);
    return this;
  }

  function waitFirst(time) {
    tasks.unshift(
      () => new Promise((resolve) => setTimeout(resolve, time * 1000))
    );
    return this;
  }

  function execute() {
    (async () => {
      for (const task of task) {
        await task();
      }
    })();
    return this;
  }

  return {
    wait,
    do: doSomething,
    waitFirst,
    execute,
  };
}