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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Set up TestCafe and TypeScript JavaScript End-to-End Automation Testing Framework From Scratch
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • Debugging With Confidence in the Age of Observability-First Systems
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  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 user avatar
Maulik Suchak
·
Jan. 01, 25 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!