-1

I am new to JavaScript and, am not able to understand why the output of the following code:-

let promise = new Promise((res, rej) => {
  setTimeout(() => {
    console.log("promise executed");
  }, 10000);
  res("async executed");
});

console.log("sync programming in progress");

promise
  .then((res) => {
    console.log(res);
  })
  .catch((err) => console.log("unexpected error"));

console.log("sync program done");

is:-

sync programming in progress
sync program done
async executed
promise executed

and not:-

sync programming in progress
sync program done
promise executed
async executed

additionally, console.log("async executed") is not getting lagged for 10 seconds, instead, it gets executed immediately after the two synchronous console.log

Rosh
  • 31
  • 5
  • 1
    `setTimeout` is a function that immediately returns and execution will continue below it like with any other function call. It is the callback that is given to `setTimeout` that executes later, not the code that follows below the `setTimeout` call. – trincot Oct 19 '22 at 14:20
  • 1
    @trincot, I get it, thanks mate for a clear explanation. – Rosh Oct 19 '22 at 14:29
  • It's answered here (the thing they are wrapped in a promise don't have much effect in your case): [Sequence of execution for JavaScript setTimeout](https://stackoverflow.com/questions/50543496/sequence-of-execution-for-javascript-settimeout) – FZs Oct 20 '22 at 06:15

1 Answers1

1

As commented by @trincot, setTimeout is a function that immediately returns and execution will continue below it like with any other function call. It is the callback that is given to setTimeout that executes later, not the code that follows below the setTimeout call.

Rosh
  • 31
  • 5