🔄

Understanding JavaScript Promise Objects

Apr 23, 2025

Promise Object in JavaScript

Overview

  • Promise: Represents eventual completion or failure of an asynchronous operation.
  • States:
    • Pending: Initial state, neither fulfilled nor rejected.
    • Fulfilled: Operation completed successfully.
    • Rejected: Operation failed.
  • Resolved: Promise is settled to match the eventual state of another promise.

Using Promises

  • Promises allow asynchronous methods to return values like synchronous methods.
  • Promise handlers (then, catch, finally) are triggered based on the promise state.
  • Chained Promises: Allows further actions to be associated with the settled promise.
    • then(): Takes two arguments; handlers for fulfilled and rejected cases.
    • catch(): Handles promise rejections.
    • finally(): Executes when promise is settled, regardless of outcome.

Promise Methods

  • Static Methods:
    • Promise.all(): Fulfills when all promises are fulfilled, rejects if any are rejected.
    • Promise.allSettled(): Fulfills when all promises settle.
    • Promise.any(): Fulfills when any promise fulfills, rejects if all reject.
    • Promise.race(): Settles when any promise settles.
    • Promise.resolve(): Returns a fulfilled promise.
    • Promise.reject(): Returns a rejected promise.
  • Instance Methods:
    • Promise.prototype.then(): Appends fulfillment and rejection handlers.
    • Promise.prototype.catch(): Appends a rejection handler.
    • Promise.prototype.finally(): Appends a handler for when promise is settled.

Concepts

  • Thenables: Objects implementing the then method, allowing them to be used like promises.
  • Promise Concurrency: Promises can be executed concurrently using methods like Promise.all.
  • Job Queue: JavaScript executes promises by adding them to a job queue, ensuring asynchronous execution.

Examples

  • Basic Example: Promise with setTimeout to simulate async behavior.
  • Diverse Situations: Handling errors and chaining promises.
  • Advanced Example: Demonstrates promise creation and fulfillment logging.
  • XHR Loading: Using promises to handle image loading with XMLHttpRequest.

Additional Topics

  • Incumbent Settings Object: Ensures the correct environment is used for executing JavaScript code in specific contexts.

Specifications and Compatibility

  • ECMAScript: Defined under ECMAScript 2026 Language Specification.

These notes cover the key concepts and methods related to JavaScript Promises, providing a foundational understanding of how Promises work and how they can be used to handle asynchronous operations efficiently.