Search code examples
javascriptasynchronouspromisesettimeoutes6-promise

How to nest promises in JS and have them resolved in different times?


I thought that by running the code below the numbers 1, 2 and 4 would show up on the screen within 1 second after the other. But they show up at the same time.

As my nested resolve is inside a setTimeout(), shouldn’t they be resolved only one second after the previous one?

var test = document.getElementById("test");

new Promise(function(resolve, reject) {
  setTimeout(() => resolve(1), 1000);
}).then(result => {
  test.innerHTML += result + "<br>";
  return new Promise(function(resolve, reject) {
    setTimeout(() => resolve(result * 2, 2000));
  });
}).then(result => {
  test.innerHTML += result + "<br>";
  return new Promise(function(resolve, reject) {
    setTimeout(() => resolve(result * 2, 3000));
  });
}).then(result => {
  test.innerHTML += result;
});

Solution

  • pass the second argument correctly for the setTimeout

    new Promise(function(resolve, reject) {
      setTimeout(() => resolve(1), 1000);
    }).then(result => {
      console.log(result)
      return new Promise(function(resolve, reject) {
        setTimeout(() => resolve(result * 2),2000);
      });
    }).then(result => {
     console.log(result)
      return new Promise(function(resolve, reject) {
        setTimeout(() => resolve(result * 2),3000);
      });
    }).then(result => {
      console.log(result)
    });