Home Web Front-end JS Tutorial Building XPromise: A Deep Dive into Custom JavaScript Promises

Building XPromise: A Deep Dive into Custom JavaScript Promises

Oct 26, 2024 pm 01:40 PM

JavaScript is known for its asynchronous nature, enabling operations like data fetching, animations, and file handling without blocking other processes. Promises are at the heart of handling asynchronous operations gracefully, making our code cleaner and more manageable. This project, XPromise, is a custom implementation of JavaScript Promises, helping us explore how the Promise mechanism works internally.

You can check out the full implementation on GitHub.

What is a Promise?

A Promise in JavaScript is a special object representing the eventual completion or failure of an asynchronous operation. With Promises, we can queue up operations to run after the completion of a task, even if we don’t know when it will be done. Here’s what makes a Promise unique:

  1. Three States: A Promise can be Pending, Fulfilled, or Rejected.
  2. Immutable State Change: Once a Promise is resolved (fulfilled or rejected), it cannot change states.
  3. Chaining with .then and .catch: Promises provide .then() for handling fulfilled values and .catch() for errors, making them composable.

Building XPromise: A Deep Dive into Custom JavaScript Promises

Why Build a Custom Promise?

Creating a custom Promise, like XPromise, provides a deeper understanding of its inner workings:

  • State Management: We handle states in a way that ensures only one final state.
  • Callback Queuing: The Promise must queue up callbacks to be executed once it’s resolved.
  • Error Handling: It includes a way to handle asynchronous errors gracefully, emulating native Promise behavior.

Project Walkthrough

Let’s go through the code for XPromise, exploring each component that makes it work just like JavaScript’s native Promises.

Setting Up States and Basic Structure

XPromise starts by defining three states: PENDING, FULFILLED, and REJECTED.

const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class XPromise {
  constructor(executor) {
    this.state = PENDING;
    this.queue = [];
    doResolve(this, executor);
  }
  // ...
}
Copy after login
Copy after login
  1. Constructor and Initial Setup:
    • XPromise accepts an executor function, which runs immediately.
    • this.state keeps track of the current state, while this.queue holds all functions queued up by .then() calls.

Adding the then, catch, and finally Methods

With then, catch, and finally, we handle fulfilled, rejected, and cleanup scenarios. Here’s how XPromise achieves chaining:

const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class XPromise {
  constructor(executor) {
    this.state = PENDING;
    this.queue = [];
    doResolve(this, executor);
  }
  // ...
}
Copy after login
Copy after login
  1. then: The then method creates a new XPromise instance and stores it along with onFulfilled and onRejected callbacks. This ensures that the next Promise in the chain receives the output of the previous one.
  2. catch: A shorthand for handling errors, equivalent to calling then(null, onRejected).
  3. finally: Handles cleanup actions that execute regardless of the Promise’s outcome.

Managing Resolved States with handle

The handle function decides if the Promise is still pending or resolved. If it’s pending, the handler is added to the queue to be executed later. If the Promise is resolved, it immediately processes the handler.

then(onFulfilled, onRejected) {
  const promise = new XPromise(() => {});
  handle(this, { promise, onFulfilled, onRejected });
  return promise;
}

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

finally(onFinally) {
  return this.then(onFinally, onFinally);
}
Copy after login

Resolving and Rejecting Promises

Fulfilled and rejected Promises need special functions to handle their results. Here’s how XPromise achieves it:

function handle(promise, handler) {
  while (promise.state !== REJECTED && promise.value instanceof XPromise) {
    promise = promise.value;
  }

  if (promise.state === PENDING) {
    promise.queue.push(handler);
  } else {
    handleResolved(promise, handler);
  }
}
Copy after login
  1. Fulfill and Reject:

    • fulfill and reject finalize the Promise, updating its state and value.
    • If value is a Promise or thenable, we defer to doResolve to ensure it’s handled correctly.
  2. Finalizing Queued Handlers:

    • Once the Promise is resolved, finale iterates through the queue to execute all handlers in order.

The Executor Function doResolve

The doResolve function runs the executor safely by wrapping resolve and reject calls, preventing any further state changes if they are called multiple times.

function fulfill(promise, value) {
  if (value === promise) {
    return reject(promise, new TypeError());
  }

  if (value && (typeof value === "object" || typeof value === "function")) {
    let then;
    try {
      then = value.then;
    } catch (e) {
      return reject(promise, e);
    }

    if (typeof then === "function") {
      return doResolve(promise, then.bind(value));
    }
  }

  promise.state = FULFILLED;
  promise.value = value;
  finale(promise);
}

function reject(promise, reason) {
  promise.state = REJECTED;
  promise.value = reason;
  finale(promise);
}
Copy after login

Example Usage of XPromise

Now that we have a working XPromise, let’s try it out with a simple example:

function doResolve(promise, executor) {
  let called = false;
  function wrapFulfill(value) {
    if (called) return;
    called = true;
    fulfill(promise, value);
  }

  function wrapReject(reason) {
    if (called) return;
    called = true;
    reject(promise, reason);
  }
  try {
    executor(wrapFulfill, wrapReject);
  } catch (e) {
    wrapReject(e);
  }
}
Copy after login

Key Takeaways

Reimplementing Promises from scratch provides hands-on insight into how asynchronous programming is managed in JavaScript:

  • State Management ensures that the Promise resolves only once, staying either fulfilled or rejected.
  • Callback Queueing allows for handling multiple chained .then() calls effectively.
  • Error Handling with catch and finally helps in handling asynchronous errors gracefully.

To dive deeper into the code, check out the XPromise project on GitHub. Experiment with the code and feel free to customize it to explore more advanced features, such as Promise race conditions, chaining, and nesting!

The above is the detailed content of Building XPromise: A Deep Dive into Custom JavaScript Promises. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles