DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Set up TestCafe and TypeScript JavaScript End-to-End Automation Testing Framework From Scratch
  • PWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOS
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look

Trending

  • A Non-Expiring AKS Deployment Token Could Read Secrets Across Three Namespaces
  • Genkit Flows on Kubernetes, Routed by a Decision Model: senro + jev in Go
  • PII Detection Before RAG Ingestion: Screening Documents in C#
  • Part 4: Multi-Agent Orchestration — Pairing Goose With Quarkus Flow State Machines

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. JavaScript
  4. Understanding JavaScript Promises: A Comprehensive Guide to Create Your Own From Scratch

Understanding JavaScript Promises: A Comprehensive Guide to Create Your Own From Scratch

Understanding promises — from creation, chaining, and error handling to advanced features — empowers developers to write cleaner and more maintainable asynchronous code.

By 
Maulik Suchak
·
Jan. 01, 25 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
5.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Asynchronous programming is an essential pillar of modern web development. Since the earliest days of Ajax, developers have grappled with different techniques for handling asynchronous tasks. JavaScript’s single-threaded nature means that long-running operations — like network requests, reading files, or performing complex calculations — must be done in a manner that does not block the main thread. Early solutions relied heavily on callbacks, leading to issues like “callback hell,” poor error handling, and tangled code logic.

Promises offer a cleaner, more structured approach to managing async operations. They address the shortcomings of raw callbacks by providing a uniform interface for asynchronous work, enabling easier composition, more readable code, and more reliable error handling. For intermediate web engineers who already know the basics of JavaScript, understanding promises in depth is critical to building robust, efficient, and maintainable applications.

In this article, we will:

  1. Explain what a promise is and how it fits into the JavaScript ecosystem.
  2. Discuss why promises were introduced and what problems they solve.
  3. Explore the lifecycle of a promise, including its three states.
  4. Provide a step-by-step example of implementing your own simplified promise class to deepen your understanding.

By the end of this article, you will have a solid grasp of how promises work and how to use them effectively in your projects.

What Is a Promise?

A promise is an object representing the eventual completion or failure of an asynchronous operation. Unlike callbacks — where functions are passed around and executed after a task completes — promises provide a clear separation between the asynchronous operation and the logic that depends on its result.

In other words, a promise acts as a placeholder for a future value. While the asynchronous operation (such as fetching data from an API) is in progress, you can attach handlers to the promise. Once the operation completes, the promise either:

  • Fulfilled (Resolved): The promise successfully returns a value.
  • Rejected: The promise fails and returns a reason (usually an error).
  • Pending: Before completion, the promise remains in a pending state, not yet fulfilled or rejected.

The key advantage is that you write your logic as if the value will eventually be available. Promises enforce a consistent pattern: an asynchronous function returns a promise that can be chained and processed in a linear, top-down manner, dramatically improving code readability and maintainability.

Why Do We Need Promises?

Before the introduction of promises, asynchronous programming in JavaScript often relied on nesting callbacks:

JavaScript
 
getDataFromServer((response) => {
  parseData(response, (parsedData) => {
    saveData(parsedData, (saveResult) => {
      console.log("Data saved:", saveResult);
    }, (err) => {
      console.error("Error saving data:", err);
    });
  }, (err) => {
    console.error("Error parsing data:", err);
  });
}, (err) => {
  console.error("Error fetching data:", err);
});


This pattern easily devolves into what is commonly known as “callback hell” or the “pyramid of doom.” As the complexity grows, so does the difficulty of error handling, code readability, and maintainability.

Promises solve this by flattening the structure:

JavaScript
 
getDataFromServer()
  .then(parseData)
  .then(saveData)
  .then((result) => {
    console.log("Data saved:", result);
  })
  .catch((err) => {
    console.error("Error:", err);
  });


Notice how the .then() and .catch() methods line up vertically, making it clear what happens sequentially and where errors will be caught. This pattern reduces complexity and helps write code that is closer in appearance to synchronous logic, especially when combined with async/await syntax (which builds on promises).

The Three States of a Promise

A promise can be in one of three states:

  1. Pending: The initial state. The async operation is still in progress, and the final value is not available yet.
  2. Fulfilled (resolved): The async operation completed successfully, and the promise now holds a value.
  3. Rejected: The async operation failed for some reason, and the promise holds an error or rejection reason.

A promise’s state changes only once: from pending to fulfilled or pending to rejected. Once settled (fulfilled or rejected), it cannot change state again.

Consider the lifecycle visually:

┌──────────────────┐ | Pending | └───────┬──────────┘ | v ┌──────────────────┐ | Fulfilled | └──────────────────┘ or ┌──────────────────┐ | Rejected | └──────────────────┘


Building Your Own Promise Implementation

To fully grasp how promises work, let’s walk through a simplified custom promise implementation. While you would rarely need to implement your own promise system in production (since the native Promise API is robust and well-optimized), building one for learning purposes is instructive.

Below is a simplified version of a promise-like implementation. It’s not production-ready, but it shows the concepts:

JavaScript
 
const PROMISE_STATUS = {
  pending: "PENDING",
  fulfilled: "FULFILLED",
  rejected: "REJECTED",
};

class MyPromise {
  constructor(executor) {
    this._state = PROMISE_STATUS.pending;
    this._value = undefined;
    this._handlers = [];

    try {
      executor(this._resolve.bind(this), this._reject.bind(this));
    } catch (err) {
      this._reject(err);
    }
  }

  _resolve(value) {
    if (this._state === PROMISE_STATUS.pending) {
      this._state = PROMISE_STATUS.fulfilled;
      this._value = value;
      this._runHandlers();
    }
  }

  _reject(reason) {
    if (this._state === PROMISE_STATUS.pending) {
      this._state = PROMISE_STATUS.rejected;
      this._value = reason;
      this._runHandlers();
    }
  }

  _runHandlers() {
    if (this._state === PROMISE_STATUS.pending) return;

    this._handlers.forEach((handler) => {
      if (this._state === PROMISE_STATUS.fulfilled) {
        if (handler.onFulfilled) {
          try {
            const result = handler.onFulfilled(this._value);
            handler.promise._resolve(result);
          } catch (err) {
            handler.promise._reject(err);
          }
        } else {
          handler.promise._resolve(this._value);
        }
      }

      if (this._state === PROMISE_STATUS.rejected) {
        if (handler.onRejected) {
          try {
            const result = handler.onRejected(this._value);
            handler.promise._resolve(result);
          } catch (err) {
            handler.promise._reject(err);
          }
        } else {
          handler.promise._reject(this._value);
        }
      }
    });

    this._handlers = [];
  }

  then(onFulfilled, onRejected) {
    const newPromise = new MyPromise(() => {});
    this._handlers.push({ onFulfilled, onRejected, promise: newPromise });
    if (this._state !== PROMISE_STATUS.pending) {
      this._runHandlers();
    }
    return newPromise;
  }

  catch(onRejected) {
    return this.then(null, onRejected);
  }
}

// Example usage:
const p = new MyPromise((resolve, reject) => {
  setTimeout(() => resolve("Hello from MyPromise!"), 500);
});

p.then((value) => {
  console.log(value); // "Hello from MyPromise!"
  return "Chaining values";
})
  .then((chainedValue) => {
    console.log(chainedValue); // "Chaining values"
    throw new Error("Oops!");
  })
  .catch((err) => {
    console.error("Caught error:", err);
  });


What’s happening here?

  1. Construction: When you create a new MyPromise(), you pass in an executor function that receives _resolve and _reject methods as arguments.
  2. State and Value: The promise starts in the PENDING state. Once resolve() is called, it transitions to FULFILLED. Once reject() is called, it transitions to REJECTED.
  3. Handlers Array: We keep a queue of handlers (the functions passed to .then() and .catch()). Before the promise settles, these handlers are stored in an array. Once the promise settles, the stored handlers run, and the results or errors propagate to chained promises.
  4. Chaining: When you call .then(), it creates a new MyPromise and returns it. Whatever value you return inside the .then() callback becomes the result of that new promise, allowing chaining. If you throw an error, it’s caught and passed down the chain to .catch().
  5. Error Handling: Similar to native promises, errors in .then() handlers immediately reject the next promise in the chain. By having a .catch() at the end, you ensure all errors are handled.

While this code is simplified, it reflects the essential mechanics of promises: state management, handler queues, and chainable operations.

Best Practices for Using Promises

  1. Always return promises: When writing functions that involve async work, return a promise. This makes the function’s behavior predictable and composable.
  2. Use .catch() at the end of chains: To ensure no errors go unhandled, terminate long promise chains with a .catch().
  3. Don’t mix callbacks and promises needlessly: Promises are designed to replace messy callback structures, not supplement them. If you have a callback-based API, consider wrapping it in a promise or use built-in promisification functions.
  4. Leverage utility methods: If you’re waiting on multiple asynchronous operations, use Promise.all(), Promise.race(), Promise.allSettled(), or Promise.any() depending on your use case.
  5. Migrate to async/await where possible: Async/await syntax provides a cleaner, more synchronous look. It’s generally easier to read and less prone to logical errors, but it still relies on promises under the hood.

Conclusion

Promises revolutionized how JavaScript developers handle asynchronous tasks. By offering a structured, composable, and more intuitive approach than callbacks, promises laid the groundwork for even more improvements, like async/await. For intermediate-level engineers, mastering promises is essential. It ensures you can write cleaner, more maintainable code and gives you the flexibility to handle complex asynchronous workflows with confidence.

We covered what promises are, why they are needed, how they work, and how to use them effectively. We also explored advanced techniques like Promise.all() and wrote a simple promise implementation from scratch to illustrate the internal workings. With this knowledge, you’re well-equipped to tackle asynchronous challenges in your projects, building web applications that are more robust, maintainable, and ready for the real world.

JavaScript Scratch (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Set up TestCafe and TypeScript JavaScript End-to-End Automation Testing Framework From Scratch
  • PWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOS
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook