Here is the exact order of what goes on. Before we begin, you should note that Promise objects are always in one of three states:
- Waiting for evaluation to complete.
- Resolved with a final value.
- Rejected with a "reason" value.
First, promise1
is assigned a promise that is in the "Resolved" state with a final value of [1,2,3]:
var promise1 = Promise.resolve([1, 2, 3]);
Next, we ask that, once promise1
enters its resolved state, we log its final value. However, .then(), .catch(), etc. in promises are never evaluated until the whole program is passed through and execution enters the Javascript event loop. Thus, this chunk of code registers the future action that is to be completed but does not actually complete it; this chunk of code returns right away without completion occurring.
promise1.then((value) => {
console.log(value);
// expected output: Array [1, 2, 3]
});
After that, we print some text:
console.log('end of script');
At this point, Javascript's execution returns to its event loop, it finds the .then()
that we registered earlier, and it carries out the relevant function ((value) => console.log(value)
).
There is a helpful article describing how the event loop works with promises here: https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5