in

How to chain functions asynchronously using javascript?


I was asked to create such an object called foo that can chain the function log and wait.

For example:

foo.log('breakfast').wait(3000).log('lunch').wait(3000).dinner();

In this scenario it prints foo first and then wait 3 seconds and prints lunch, then after 3 seconds it prints dinner.

I tried something like this but it doesn’t work, what did I miss?

var foo = {
  log: function(text){
    console.log(text);
    return foo;
  },
  
  wait: function(time) {
    setTimeout(function() {
      return foo;
    }, time);
  }
}

foo.log('breakfast').wait(3000).log('lunch').wait(3000).dinner();



Source: https://stackoverflow.com/questions/70541130/how-to-chain-functions-asynchronously-using-javascript

a code comprehensive analysis platform

A simple control app for theoretical driving lessons in Brazil