DEV Community

Tamilselvan K
Tamilselvan K

Posted on • Edited on

Day-46 Understanding Promises in JavaScript – A Beginner-Friendly Guide

What is a Promise in JavaScript?

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

It’s like a placeholder for a value that will be available now, later, or never.

Why Promises?

In JavaScript, many operations take time — like fetching data from an API or reading a file. Without Promises, we used callback functions, which often led to "callback hell" — a messy, nested structure of callbacks that was hard to read and maintain.

Promises help handle asynchronous operations in a more readable and manageable way.


Promise States

A Promise has three states:

  1. Pending – The initial state, neither fulfilled nor rejected.
  2. Fulfilled – The operation completed successfully.
  3. Rejected – The operation failed.
        +-------------------+
        |     Pending        |
        +-------------------+
          /              \
         /                \
+-------------+      +-------------+
|  Fulfilled  |      |  Rejected   |
+-------------+      +-------------+
Enter fullscreen mode Exit fullscreen mode

Creating a Promise

const myPromise = new Promise((resolve, reject) => {
    const success = true;

    if (success) {
        resolve(" Promise fulfilled!");
    } else {
        reject(" Promise rejected!");
    }
});
Enter fullscreen mode Exit fullscreen mode

Consuming a Promise

myPromise
    .then((message) => {
        console.log(message); //  Promise fulfilled!
    })
    .catch((error) => {
        console.log(error);   //  Promise rejected!
    })
    .finally(() => {
        console.log(" Promise is settled (either fulfilled or rejected)");
    });
Enter fullscreen mode Exit fullscreen mode

Callbacks vs. Promises

Callbacks Promises
Callback hell (nested code) Cleaner, chainable .then()
Harder to manage errors Error handling via .catch()
Less readable More readable
Traditional async handling Modern async handling

Promise Example with API (Fetch)

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => response.json())
    .then(data => console.log("Post:", data))
    .catch(error => console.log("Error:", error));
Enter fullscreen mode Exit fullscreen mode

Conclusion

Promises are a powerful way to handle asynchronous operations in JavaScript. They make code cleaner, more readable, and easier to manage than traditional callbacks.

Top comments (0)