Stubborn
Stubborn

Reputation: 330

Why does the second promise not get resolved if both promises are constructed using same function

Below code only prints "delay of 2000 executed". I get it that a promise only executes once. But this is not the same promise that I create in next line

function later(delayMillis) {
  return new Promise(function(resolve) {
    setTimeout(()=>{console.log('delay of ' + delayMillis + ' executed');}, delayMillis);
  });
}

(async () => {
   await later(2000);
   await later(3000);
   console.log('This should print after minimum 5 seconds');
})();

If I change the function to return execute resolve instead of the console log I specified, I do get the output "This should print after minimum 5 second". Why is it that both promises execute in this case?

function later(delayMillis) {
  return new Promise(function(resolve) {
    setTimeout(resolve, delayMillis);
  });
}

(async () => {
   await later(2000);
   await later(3000);
   console.log('This should print after minimum 5 seconds');
})();

Upvotes: 0

Views: 287

Answers (2)

The promises are all built in such a form that they listen for the resolve. It is almost like handling an asynchronous event, which resolve stands for.

new Promise((res)=>{res('This should print')}).then(console.log);

is a general case.

Your case is similar.

Upvotes: 0

Amr Al-Gendi
Amr Al-Gendi

Reputation: 98

You need to edit the later function to be as follows:

function later(delayMillis) {
  return new Promise(function(resolve) {
    setTimeout(()=>{console.log('delay of ' + delayMillis + ' executed'); resolve();}, delayMillis);
  });
}

The reason is because await does not move to the next instruction unless it is resolved or rejected.

You tried using either console.log or resolve. Why not use both!!

Upvotes: 1

Related Questions