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"?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With