Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sleep a method in javascript method chaining

Tags:

javascript

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.

Right now I am calling the function like

lazyMan("John", console.log).eat("banana").sleep(5).then(d => {d.eat("apple");});.

Here is my code

function lazyMan(name, logFn) {
  logFn(name);
  return {
    eat: function(val) {
      console.log(val);
      return this;
    },
    sleep: function(timer) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log(`Sleeping for ${timer} seconds`);
          resolve(this);
        }, timer * 1000);
      }).then(d => this);
    }
  };
}
lazyMan("John", console.log)
  .eat("banana")
  .sleep(5)
  .then(d => {
    d.eat("apple");
  });

Is there a way I can modify my function to call it like lazyMan("John", console.log).eat("banana").sleep(5).eat("apple") and get the output in same order

I have gone through Add a sleep method in a object method chain(JS)

like image 540
brk Avatar asked Feb 19 '21 10:02

brk


1 Answers

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.

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

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.

like image 85
VLAZ Avatar answered Sep 21 '22 22:09

VLAZ