Javascript is single threaded (mostly). To allow JS to scale it relies heavily on asynchronous execution of code. So imagine making a phone call, you ask a question, the person on the other end of the line has to look up the answer, so you wait. All the time your waiting you're not doing anything. This is wasteful of your time.
Now imagine doing the same thing but this time you tell the person on the other end of the line to tell you when they've got the answer. You hang up and do something else. When the other person has finished they call you back to give you the answer to your question. This is a much more efficient use of your time.
In your code the Promise is you making the phone call. The then
is the person you've called calling you back when they have the result and your (the person making the call that is) the Js thread.
So you do:
//1
console.log(1);
You then call someone (promise) and ask for them to do some work:
let p = Promise.resolve(2); //nothing printed here
They say they'll call you back:
.then(...) //nothing printed here
You do other work
//3
console.log(3);
They call you back:
//2
val => console.log(val)
1
3
2
but since the promise resolving is done synchronously
No it's not promises are resolved asynchronously
console.log
is immediate execution. So imagine the person you've just hung up on tries to call you back straight away. But you don't answer yet because you just need to finish this other task. Then you answer.