96. Introduction to Promises
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation, and its resulting value. Promises solve 'callback hell' by providing a cleaner, sequential flow.
Promise States
A Promise is always in one of three mutually exclusive states:
- Pending: The initial state; the operation has not finished yet.
- Fulfilled (Resolved): The operation completed successfully, and the Promise now has a resulting value.
- Rejected: The operation failed, and the Promise now has a reason for the failure (an error).
Creating a Simple Promise
javascript const myPromise = new Promise((resolve, reject) => { // Simulate a successful operation after 1 second setTimeout(() => { const randomNumber = Math.random(); if (randomNumber > 0.5) { resolve('Data successfully fetched!'); // Success path } else { reject(new Error('Network connection failed.')); // Failure path } }, 1000); });
In the next lesson, we learn how to consume this promise.