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

Time:08-30

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');
})();

CodePudding user response:

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!!

CodePudding user response:

This is a question up there. 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. console.log is another kind here.

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

is a general case.

Your case is similar.

You and me shouldn't know just why all happens, but how to use it!

  • Related