Promises in JavaScript
A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value.
What is a Promise?
Promises are used to handle asynchronous operations in JavaScript. A Promise represents a value that may be available now, later, or never.
Simple Definition
A Promise represents the result of an asynchronous operation.
Promise States
A Promise can have three states: Pending, Fulfilled, or Rejected.
A Promise starts in the Pending state and eventually becomes Fulfilled or Rejected.
Example 1: Creating a Promise
We can create a Promise using the Promise constructor.
const promise = new Promise(function(resolve, reject) {
resolve("Operation completed successfully");
});
console.log("Promise created successfully");
Example 2: Promise Result
A Promise can be resolved with a value. The resolved value can then be used by JavaScript.
function getData() {
const promise =
Promise.resolve("Data received successfully");
console.log("Data received successfully");
}
getData();
Example 3: Promise Rejection
A Promise can also be rejected when an operation fails.
const promise =
Promise.reject("Something went wrong");
console.log("Promise rejected: Something went wrong");
Why Use Promises?
Important Benefits
• Makes asynchronous code easier to manage.
• Provides clear success and error handling.
• Reduces deeply nested callback code.
• Supports then() and catch() methods.
• Promises are the foundation for async and await.
Important Note
The CIIT JavaScript Compiler executes code inside a Web Worker and displays console output in the terminal.
The interactive examples on this page are written in a compiler-safe way so the output is displayed correctly.
Summary
Promises represent the eventual result of an asynchronous operation. A Promise can be Pending, Fulfilled, or Rejected. The then() method handles successful results, while catch() handles errors.