Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Loop and promises

When I am running below code in the console, I am getting output as:

"start"
"Promise 2"
"end"
"Promise 1"

console.log("start");
Promise.resolve().then(
  () => console.log("Promise 1")
).then(console.log("Promise 2"));
console.log("end");

Can anyone explain to me why "Promise 2" is printed before "Promise 1" and "end"?

like image 434
Swapnil Gupta Avatar asked Sep 16 '26 16:09

Swapnil Gupta


1 Answers

The argument to .then() should be a function. But you wrote .then(console.log("Promise 2")), and console.log("Promise 2") is a function call, not a function. It's executed immediately, so the log message is displayed immediately, not when the promise is resolved.

Change it to a function, like you have around console.log("Promise 1"), and they'll be executed in the expected order.

console.log("start");
Promise.resolve().then(
  () => console.log("Promise 1")
).then(() => console.log("Promise 2"));
console.log("end");

end is logged first because promise resolution is asynchronous.

like image 87
Barmar Avatar answered Sep 18 '26 04:09

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!