Search code examples
javascriptpromisechaining

how to dynamic chain a promise inside a function in javascript?


I have the following exercise :

let standInLine = (() => {
  return function(logAfter) {
    return function b(seconds) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(`${seconds} has passed`)
          resolve(b(seconds));
        }, seconds * 1000);
      }) //what to do here to chain the promises
    }
  }
})();
{
  let politeLogAfter = standInLine(logAfter);
  politeLogAfter(5);
  politeLogAfter(3);
  politeLogAfter(4);
}

I need to chain the promises , in other words , I need to chain the returned promise dynamically , where I should add .then() inside the function standInLine but I dont know how to do that , any help ? The result should be :

pause 5 seconds

log “5 seconds have passed”

pause 3 seconds

log “3 seconds have passed”

pause 4 seconds

log “4 seconds have passed”


Solution

  • You can use a single promise as a queue by always using .then() on it:

    let standInLine = (() => {
      // create a queue
      let queue = Promise.resolve();
    
      return function(logAfter) {
        return function b(seconds) {
          //add to the end of the queue
          queue = queue.then(() => new Promise((resolve) => {
            setTimeout(() => {
              console.log(`${seconds} has passed`)
              resolve(b(seconds));
            }, seconds * 1000);
          }))
        }
      }
    })();
    const logAfter = 10;
    {
      let politeLogAfter = standInLine(logAfter);
      politeLogAfter(5);
      politeLogAfter(3);
      politeLogAfter(4);
    }