Why We Need .then()
Let’s start with a simple question:
Once a promise is resolved, how do we access its value?
You might think we can simply do something like:
console.log(promise.value);
But that does not work.
Why?
Because:
- The
valueandstatusof a promise are internal properties - They are not accessible directly
- JavaScript intentionally hides them from direct access
So how do we get the result? By using .then()
Creating a Simple Promise
Let’s start with a very simple promise that resolves with a string.
const myPromise = new Promise((resolve, reject) => {
resolve("Hello World");
});
At this point:
- The promise is already resolved.
- But we still haven’t accessed its value.
Using .then() to Access the Value
To get the resolved value, we use the .then() method.
myPromise.then((value) => {
console.log(value);
});
Output:
Hello World
What Is .then()?
The .then() method allows us to register a callback function that runs when the promise is fulfilled.
It accepts two optional functions:
promise.then(onFulfilled, onRejected);
onFulfilled→ runs when the promise is resolvedonRejected→ runs when the promise is rejected
Each function receives exactly one argument:
- The resolved value (for success)
- The error reason (for failure)
Using Only the Fulfilled Handler
Most of the time, we only care about the success case.
That’s why it’s very common to use .then() like this:
myPromise.then(value => {
console.log(value);
});
This works perfectly when the promise resolves successfully.
Example with Console Logs (Execution Order)
Now let’s look at an example that helps us understand when .then() actually runs.
const myPromise = new Promise((resolve) => {
resolve("Hello World");
});
myPromise.then((value) => {
console.log("Inside then:", value);
});
console.log("This is written after my promise.then()");
Output:
This is written after my promise.then() Inside then: Hello World
Why Does This Happen?
Even though the promise is already resolved, the .then() callback does not execute immediately.
Instead:
- It is placed into the microtask queue
- It runs only after the current call stack is empty
This means:
- All synchronous code runs first
- Then promise callbacks are executed
Important Concept: Subscribing to a Promise
When you call .then(), you are essentially subscribing to the result of the promise.
You’re saying:
“When this promise is fulfilled, run this function.”
That function will:
- Run automatically
- Receive the resolved value
- Execute after the main code finishes
