Promise unexpected behavior, execution order
I had no errors before updating Chrome to 58.
Further explanation: My code worked on Sunday, I was not aware of the asynchronous nature of execution , I found out about it two days later!
new Promise((s, f) => {
console.log(1);
s();
console.log(2);
})
.then(r => {console.log(3)})
console.log(4);
OUTPUT:
1
2
4
3
1- Why is "then" executed after console.log (2) ???
Possible answer: because the result of the promise is fulfilled after the body returns
2- Why is "then" executed after console.log (4) ???
source to share
Due to the asynchronous nature of promises, the handler then
will be stored in the message queue of the event loop. The elements of this queue are processed whenever the JavaScript runtime call stack is empty. Your script console.log(4);
must run before the closing function can be removed from the call stack, after which the JavaScript engine can start processing items from the message queue (assuming the closure function is a top-level function), causing the code inside to execute then
.
source to share
Thanks @PatrickRoberts for providing help:
Promises are naturally ASYNC and are executed when the next loop in the loop is executed.
source to share