Home > Mobile >  Why Javascript waits for promises to fulfil
Why Javascript waits for promises to fulfil

Time:10-22

I'm learning promises and I came across this piece of code

async function main() {
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("hello");
      resolve();
    }, 1000);
  });
  console.log("world");
}

main();

The output this produces is "hello world".

What I'm not able to understand is why the inner console log "console.log("world")" is waiting for the promise to resolve.

Am I missing something here, it would be nice if I can get some help understanding this or maybe some link to some documentation for further reading.

Thanks in advance.

CodePudding user response:

Knowledge of JS Event Loop await with promise keyword waits for the resolve or reject Fireship has a pretty good explanation https://www.youtube.com/watch?v=vn3tm0quoqE&t=587s&ab_channel=Fireship

CodePudding user response:

Because this is how promises work. They are designed to always return a clear result. Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise for more info.

  • Related