Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 64

Promises for Asynchronous Operations

This lesson is built with resources from youtube.com, dev.to and 1 more site.

Hello! Welcome to your next lesson on JavaScript.

In our last session, we took a deep dive into the JavaScript runtime, uncovering how the Event Loop, Call Stack, and the different Queues (Microtask and Macrotask) work together to handle asynchronous code without blocking the main thread. You learned that modern async tasks, like those involving Promises, get high-priority treatment via the Microtask Queue.

Today, we're going to focus on the star of that show: the Promise. This lesson is designed to help you understand the purpose of a Promise for managing asynchronous operations. We'll explore why Promises were introduced, what they are conceptually, and how they provide a much-needed structure for dealing with tasks that don't complete immediately. This is a cornerstone concept for building modern web applications and is essential for your goal of learning Next.js.

Part 1: The Problem Promises Solve

Before Promises, JavaScript relied on callback functions to handle asynchronous tasks. While functional, this approach has two major drawbacks that can make code difficult to manage, especially as applications grow.

1. Callback Hell

Imagine you need to perform a series of asynchronous steps, where each step depends on the one before it. For example: fetch user data, then use that data to fetch their posts, then use those posts to find comments. With callbacks, you end up nesting functions inside each other:

// Fictional functions using callbacks
fetchUser('id123', function(user) {
  console.log('Got user:', user.name);
  fetchPosts(user.id, function(posts) {
    console.log('Got posts:', posts.length);
    fetchComments(posts[0].id, function(comments) {
      console.log('Got comments:', comments.length);
      // And so on... this can get very deep!
    });
  });
});

This deep nesting creates a pyramid shape in the code, often called "Callback Hell" or the "Pyramid of Doom." It's hard to read, hard to reason about, and even harder to debug.

2. Inversion of Control (IoC)

This is a more subtle but critical issue. When you pass a callback to another function (especially a third-party one), you are essentially giving away control. You trust that the function will call your callback:

  • Exactly once.
  • At the right time.
  • With the correct arguments.

But what if it doesn't? What if it calls it twice, or never, or with an error? You've inverted control, handing over the reins of your program's execution to another piece of code.

To get a clear, practical demonstration of these issues and why a better solution was needed, the following video provides an excellent introduction.

JavaScript Promises -- Tutorial for Beginners

The video "JavaScript Promises -- Tutorial for Beginners" by ColorCode masterfully explains the limitations of callbacks and sets the stage for why Promises are so important. It uses a simple, relatable example to build up the problem.

Please watch from the beginning until 08:09. Focus on understanding the difference between synchronous and asynchronous code demonstrated, and how the use of callbacks to manage async operations can lead to complex, tightly-coupled code.

For a deeper textual explanation of these problems, especially the "Inversion of Control," the following article is a great resource.

JS illustrated: Promises

The article "JS illustrated: Promises" provides a concise summary of the problems with callbacks.

Read the section titled 'Callbacks'. It clearly defines Inversion of Control and Callback Hell, which are the core problems that Promises are designed to solve.


Part 2: What is a Promise? The Solution

A Promise is a special JavaScript object that acts as a placeholder for the eventual result of an asynchronous operation.

Instead of an async function taking a callback, it returns a Promise object immediately. This object "promises" to deliver a value at some point in the future. This simple change is incredibly powerful because it solves the problems we just discussed:

  1. It avoids "Inversion of Control": You get a predictable object back right away. You are now in control of what happens when the operation succeeds or fails.
  2. It helps flatten "Callback Hell": Because you have an object, you can attach methods to it, allowing for a cleaner, sequential style of code (which we'll explore in the next lesson).

The Three States of a Promise

Every Promise is in one of three mutually exclusive states. Think of it like an order you've placed online:

  1. pending: The initial state. The asynchronous operation has started but is not yet complete. (Your order is "Processing").
  2. fulfilled: The operation completed successfully, and the Promise now has a resulting value. (Your order has "Shipped").
  3. rejected: The operation failed, and the Promise now holds an error or reason for the failure. (Your order was "Cancelled").

A Promise is considered settled once it is either fulfilled or rejected. A key feature is that a Promise can only settle once. After it's fulfilled or rejected, its state and value are locked in and can never change.

This flowchart provides a great visual summary of the Promise lifecycle.

JavaScript Promise Lifecycle Flowchart
This flowchart shows a Promise starting in the `pending` state. It can then transition to either the `fulfilled` state (triggering a success handler) or the `rejected` state (triggering an error handler). The ability to return a new Promise from a handler is what enables chaining.

Creating a Promise

You create a Promise using the new Promise() constructor. It takes a single argument: a function called the executor. This executor function is run immediately and receives two arguments of its own: resolve and reject.

  • resolve(value): A function you call when your async task is successful. The value you pass becomes the fulfillment value of the Promise.
  • reject(error): A function you call when your async task fails. The error you pass becomes the rejection reason.

Here's the basic structure:

const myPromise = new Promise((resolve, reject) => {
  // Inside the executor, you start your asynchronous work.
  // For example, using setTimeout to simulate a network request.
  
  const operationWasSuccessful = true; // Let's pretend we know the outcome

  setTimeout(() => {
    if (operationWasSuccessful) {
      // If successful, call resolve with the result.
      resolve('Here is the data!');
    } else {
      // If it failed, call reject with an error.
      reject('Something went wrong.');
    }
  }, 2000); // Simulates a 2-second delay
});

console.log(myPromise); // What do you think this will log?

If you run this code, console.log(myPromise) will immediately print something like Promise { <pending> }. This is because the setTimeout is still running. After two seconds, the Promise will silently settle to either fulfilled or rejected in the background.

The following video provides a fantastic visualization of how a Promise object is created and how its internal state changes when resolve or reject is called.

JavaScript Visualized - Promise Execution

The video "JavaScript Visualized - Promise Execution" by Lydia Hallie is perfect for your preference for seeing what's happening "under the hood." It animates the creation of the Promise object and the modification of its internal state.

Watch the first minute (00:00 - 01:13). Pay close attention to the visual representation of the Promise object in memory and how its internal properties (promise state and promise result) change when resolve or reject are called.

Test your understanding!

Consider the following Promise. What will its final state be, and what will its value be?

const testPromise = new Promise((resolve, reject) => {
  let a = 1 + 1;
  if (a === 2) {
    resolve('Success');
  } else {
    reject('Failure');
  }
});
Show answer

The final state will be fulfilled, and its value will be the string 'Success'.

Explanation: The code inside the executor function runs synchronously. 1 + 1 evaluates to 2. The condition a === 2 is true, so the resolve function is called immediately with the argument 'Success'.


Conclusion

In this lesson, we established the fundamental purpose of Promises. They were created to bring order and predictability to asynchronous JavaScript.

Key Takeaways:

  • The Purpose: Promises exist to solve the problems of "Callback Hell" and "Inversion of Control," making async code more readable, manageable, and reliable.
  • The Object: A Promise is an object that acts as a placeholder for a future value.
  • The States: It can be in one of three states: pending, fulfilled, or rejected. Once settled (fulfilled or rejected), its state is immutable.
  • The Control: By returning a Promise object immediately, an async function gives control back to the calling code, which can then decide how and when to handle the eventual result.

Next Up

You now understand why Promises are so important and what they are conceptually. But how do we actually get the value out of a fulfilled Promise or handle a rejected one? In our next lesson, we will dive deep into consuming Promises, mastering the .then() method for success cases and the .catch() method for handling errors. This will be our next step toward fetching real data for your applications.