Skip to content Skip to sidebar Skip to footer

How To Sleep A Method In Javascript Method Chaining

I am trying to make a method sleep(delay) in method chaining. For this I am using setTimeout with Promise. This will require any method following the sleep to be inside the then. R

Solution 1:

You can keep a promise for your "task queue", so anything that needs to be done, will be added onto there via .then(). This provides a fluent API for scheduling stuff.

functionlazyMan(name, logFn) {
  logFn(name);
  let taskQueue = Promise.resolve();
  constaddTask = f => {
    taskQueue = taskQueue.then(f);
  }
  return {
    eat: function(val) {
      addTask(() =>console.log(`Eating [${val}]`));
      returnthis;
    },
    sleep: function(timer) {
      addTask(() =>newPromise((resolve, reject) => {
        console.log(`Start sleeping for ${timer} seconds`);
        setTimeout(() => {
          console.log(`End sleeping for ${timer} seconds`);
          resolve();
        }, timer * 1000);
      }))
      returnthis;
    }
  };
}

lazyMan("John", console.log)
  .eat("banana")
  .sleep(5)
  .eat("apple");

Note that this change means that every action is technically asynchronous. However, that's at least uniform, so it's less of a chance of a surprise when keeping it in mind.

Post a Comment for "How To Sleep A Method In Javascript Method Chaining"