I have a question regarding JavaScript promises and the execution order of the then() method when used with setTimeout. Below is the code in question:
new Promise((resolve) => setTimeout(resolve, 10000, "Resolved!")).then(console.log);
My concern is whether the then() method will be executed before the timer completes. I initially thought that the then() would be executed before the timer due to how JavaScript engines work. Here is my understanding of the process:
- The promise is created, and an executor function is passed to it.
- The executor function executes synchronously.
- The promise executor function sets up a setTimeout, which is handled by other parts of the browser environment and not the JS engine itself.
- Once the timer expires, the callback passed to setTimeout will be pushed to the macro-task queue.
- However, since the setTimeout takes a long time to finish, the JS engine moves to the then block.
- The then() method is executed, and a callback is pushed to the microtask queue.
- With an empty call stack, the JS engine first checks for any microtasks in the queue.
- It encounters the function from then() and executes it.
- At some point in the future, the setTimeout finishes executing and pushes the callback to the macro-task queue.
- The JS engine then sees the callback and executes it, which resolves the promise.
But when I run the code, it appears that my understanding is incorrect. Could someone please help me understand this topic better? Your assistance is greatly appreciated. Thank you! Here is the Stack Overflow answers that I have found which clearified some of my doubts: https://stackoverflow.com/questions/66934373/how-then-method-actually-works-in-javascript#:~:text=then()%20method%20will%20insert,get%20the%20result%20Hello%20Stackoverflow%20!