A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Introduced in ES6, Promises provide a structured, standardized abstraction over asynchronous programming, replacing error-prone nested callbacks.
1. The Three States of a Promise
A Promise exists in one of three mutually exclusive states:
1 ┌───────────────┐
2 │ PENDING │ (Initial state, operation in progress)
3 └───────┬───────┘
4 │
5 ┌───────────────┴───────────────┐
6 │ │
7 ▼ ▼
8 ┌───────────────┐ ┌───────────────┐
9 │ FULFILLED │ │ REJECTED │
10 │ (Success) │ │ (Failure) │
11 └───────────────┘ └───────────────┘
1
Pending: Initial state; the asynchronous operation is still running.
2
Fulfilled (Resolved): The operation completed successfully with a resulting value.
3
Rejected: The operation failed with a reason or error object.
Immutability Guarantee: Once a Promise transitions to Fulfilled or Rejected (termed settled), its state and value can never change again.
2. Creating a Promise: The Promise Constructor
The Promise constructor accepts an executor function with two arguments: resolve and reject.
1functionfetchServerStatus(isHealthy){
2returnnewPromise((resolve, reject)=>{
3 console.log('Initiating server health check...');