OR REACH ME ON

    Promises in JavaScript Explained with Real Code Examples

    When I was a few years into my career, one of the concepts that really changed the way I wrote JavaScript was Promises. Before async/await, Promises were the go-to way to handle asynchronous operations. Even now, understanding them deeply is important because async/await is built on top of Promises.

    What is a Promise?

    A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.

    It can be in one of three states:

    • Pending → Initial state, neither fulfilled nor rejected.

    • Fulfilled → The operation completed successfully.

    • Rejected → The operation failed.

    Basic Example

    				
    					const myPromise = new Promise((resolve, reject) => {
      const success = true;
    
      if (success) {
        resolve("The operation was successful!");
      } else {
        reject("Something went wrong.");
      }
    });
    
    myPromise
      .then(result => console.log(result))
      .catch(error => console.error(error));
    
    				
    			

    Here’s what happens:

    1. We create a new Promise.

    2. If success is true → it resolves.

    3. If success is false → it rejects.

    4. .then() handles success.

    5. .catch() handles failure.

    Real-World Example: Fetching Data

    				
    					fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then(response => response.json())
      .then(data => console.log("Post:", data))
      .catch(error => console.error("Error:", error));
    				
    			
    • fetch() returns a Promise.

    • We chain .then() calls to process the response.

    • .catch() handles errors (like network issues).

    Chaining Promises

    				
    					getUser()
      .then(user => getPosts(user.id))
      .then(posts => getComments(posts[0].id))
      .then(comments => console.log(comments))
      .catch(error => console.error(error));
    				
    			

    This pattern avoids callback hell and makes async logic easier to follow.

    Promises vs Async/Await

    Later,  async/await came along, making Promises easier to read:

    				
    					async function getData() {
      try {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
        const data = await response.json();
        console.log("Post:", data);
      } catch (error) {
        console.error("Error:", error);
      }
    }
    
    getData();
    				
    			

    But under the hood, async/await is still using Promises.

    🎯 Final Thoughts

    When I first learned Promises, it felt like a big leap from callbacks. Today, async/await makes things look simpler, but a strong grasp of Promises helps you understand how JavaScript really handles async operations.

    If you’re new, start by writing a few examples with .then() and .catch(), then refactor them into async/await. That’s the best way to master it.