Hello! Let's dive into the next step of your JavaScript journey.
In our last lesson, we uncovered the "what" and "why" of Promises. You learned that a Promise is a special object that acts as a placeholder for a future value, saving us from the complexities of "Callback Hell." We explored its three states: pending, fulfilled, and rejected.
Today, we'll answer the most important question: now that we have this Promise object, how do we actually use it? This lesson focuses on consuming Promises. You will learn how to get the value from a successful operation using the .then() method and how to gracefully handle failures using the .catch() method. Mastering this is fundamental for fetching data and managing asynchronous events, which are at the heart of modern applications built with frameworks like Next.js.
The Two Paths of a Promise
Once an asynchronous operation starts, its corresponding Promise is pending. From there, it can only go down one of two paths: it either succeeds (is fulfilled) or it fails (is rejected). We use specific methods to "subscribe" to these outcomes.
.then()is for the success path..catch()is for the failure path.
This simple diagram illustrates the flow perfectly:

Let's explore each path in detail.
Part 1: Handling Success with .then()
The primary way to interact with a Promise is through its .then() method. You attach a callback function to .then(), and JavaScript guarantees that this function will be called if—and only if—the Promise is fulfilled.
The fulfillment value (the data passed to the resolve() function we saw last lesson) is passed as the first and only argument to your .then() callback.
The article 'Promise' on javascript.info provides a clear, foundational explanation of how to use .then() to consume a Promise. It's a great reference for the syntax.
Read the section titled 'Consumers: then, catch', focusing specifically on the sub-section 'then'. Notice how the first argument to .then() is a function that receives the result of the resolved Promise.
Here's a practical example building on what we learned previously:
// This Promise simulates fetching user data successfully after 1.5 seconds.
const fetchUserData = new Promise((resolve, reject) => {
setTimeout(() => {
const userData = { id: 1, name: 'John Doe', email: 'john.doe@example.com' };
resolve(userData); // The operation was a success!
}, 1500);
});
console.log('Started fetching user data...'); // This runs immediately.
console.log(fetchUserData); // This will log: Promise { <pending> }
// Here's how we consume the Promise:
fetchUserData.then((data) => {
// This code runs ONLY after the Promise is fulfilled.
console.log('Promise fulfilled!');
console.log('Received data:', data);
});
If you run this, you'll see "Started fetching..." and the pending Promise log immediately. Then, about 1.5 seconds later, the message from inside the .then() callback will appear with the user data.
Under the Hood: .then() and the Microtask Queue
You might be wondering how JavaScript makes this work. Since you enjoy deep dives, let's connect this to our last discussion on the Event Loop.
When you call .then() on a Promise, you're not just passing a callback; you are creating what's called a "promise reaction record." This record contains your handler function and is attached to the Promise. When the Promise resolves, the JavaScript engine doesn't execute your handler immediately. Instead, it places your handler into the Microtask Queue.
As we learned, the Event Loop will always process everything in the Microtask Queue before moving on to anything else (like a setTimeout callback from the Macrotask Queue) as soon as the main Call Stack is empty.
This video provides an excellent visualization of this exact process.
JavaScript Visualized - Promise Execution
The video 'JavaScript Visualized - Promise Execution' by Lydia Hallie animates how .then() registers a handler and how that handler gets scheduled in the microtask queue upon promise resolution. This is a perfect visual for understanding the underlying mechanics.
Watch from 01:13 to 04:36. Pay close attention to: How calling .then() creates a 'promise reaction record'. How resolve() triggers the handler to be placed in the 'microtask queue'. The step-by-step flow showing the call stack, web APIs (for setTimeout), and the microtask queue working together.
Test your understanding!
Given the following code, in what order will the numbers 1, 2, and 3 be logged to the console?
console.log(1);
const promise = new Promise((resolve) => {
resolve();
});
promise.then(() => {
console.log(2);
});
console.log(3);
Show answer
The output will be: 1, 3, 2.
Explanation:
console.log(1)is executed synchronously.- The Promise is created and resolves immediately. This queues the
.then()callback in the Microtask Queue. console.log(3)is executed synchronously.- The main script finishes, and the Call Stack is empty. The Event Loop checks the Microtask Queue and finds the waiting callback.
- The
.then()callback is executed, logging2.
Part 2: Handling Failure with .catch()
What happens when things go wrong? If an asynchronous operation fails (e.g., a network error, a file not found), the Promise is rejected. Trying to use .then() on a rejected Promise won't work as expected. For this, we use the .catch() method.
.catch() is syntactic sugar—a cleaner, more readable way—of writing .then(null, onRejected). It's designed specifically to handle rejections.
Promises - 33 JavaScript Concepts
The article 'Promises - 33 JavaScript Concepts' gives a great overview of the consuming methods, including a clear explanation and example of using .catch() for error handling.
Read the section 'Consuming Promises: then, catch, finally', focusing on the parts about .then() and .catch(). Note the comparison of .catch(onRejected) to .then(undefined, onRejected).
Let's see it in action:
// This Promise simulates a failing network request.
const failingFetch = new Promise((resolve, reject) => {
setTimeout(() => {
// We create an Error object, which is a best practice.
const error = new Error('Network timeout. Could not fetch data.');
reject(error); // The operation failed!
}, 2000);
});
failingFetch
.then((data) => {
// This will NEVER run because the Promise is rejected.
console.log('Success:', data);
})
.catch((error) => {
// This code WILL run after the Promise is rejected.
console.error('An error occurred!'); // Using console.error is conventional for errors.
console.error(error.message); // Logs: 'Network timeout. Could not fetch data.'
});
This .then().catch() chain is the most common and readable pattern for consuming Promises. You "try" to get the success value with .then(), and you "catch" any errors that might happen along the way.
The following video walks through creating and consuming Promises that can either resolve or reject, demonstrating both .then() and .catch().
JavaScript Promises -- Tutorial for Beginners
In 'JavaScript Promises -- Tutorial for Beginners', the instructor provides a very clear, step-by-step walkthrough of handling both fulfilled and rejected Promises.
Watch from 10:30 to 16:35. This segment covers: The three states of a Promise (pending, fulfilled, rejected). Consuming a fulfilled Promise with .then(). Handling a rejected Promise, first by showing the two-argument version of .then(), and then by introducing the much cleaner .catch() method.
A Brief Look Ahead: Chaining
A critical concept we'll cover in the next lesson is that .then() and .catch() always return a new Promise. This is what allows us to chain multiple asynchronous steps together in a clean, flat structure, completely avoiding the "Pyramid of Doom."
For a quick preview, the Lydia Hallie video you watched earlier has a great segment on this.
JavaScript Visualized - Promise Execution
Let's revisit 'JavaScript Visualized - Promise Execution' for a preview of chaining. This will set us up perfectly for the next lesson.
Watch the segment from 04:36 to 06:18. Observe how each .then() call creates and returns a new Promise, allowing the next .then() in the chain to operate on its result.
Conclusion
You've now learned the essential mechanics of getting results from asynchronous operations using Promises. This is a massive step forward in writing clean, modern JavaScript.
Key Takeaways:
- Consume with
.then(): Use the.then(onFulfilled)method to register a callback that will run when a Promise is fulfilled. The callback receives the fulfillment value. - Handle Errors with
.catch(): Use the.catch(onRejected)method to register a callback that will run when a Promise is rejected. The callback receives the rejection reason (usually anErrorobject). - The Recommended Pattern: The
.then().catch()chain is the standard, most readable way to handle both success and error outcomes of a single Promise. - Asynchronous Execution: Your
.then()and.catch()handlers are run asynchronously via the Microtask Queue, ensuring they don't block the main thread.
Next Up
You know how to handle a single Promise. But what if you need to perform several asynchronous operations in a sequence, like fetching user data and then using that user's ID to fetch their posts? In our next lesson, we will master Promise Chaining, leveraging the fact that .then() returns a new Promise to create elegant, sequential asynchronous workflows.