javascriptes6-promiseasynchronous-javascript

What's the order of execution when we have callback inside promise?


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


Solution

  • 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.