JavaScript Promise
Subject: JavaScript
A Promise in JavaScript represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a cleaner alternative to deeply nested callback functions, making asynchronous code more readable and manageable.
What Is a Promise?
A Promise is an object that may be in one of three states:
- Pending – Initial state, neither fulfilled nor rejected.
 - Fulfilled – Operation completed successfully.
 - Rejected – Operation failed with an error.
 
Syntax
resolve(value)– called if the operation is successful.reject(error)– called if the operation fails.
Example 1: Basic Promise
Example 2: Simulating Asynchronous API with setTimeout
Chaining Promises
Handling Errors with catch()
Promise with finally()
Key Takeaways
- Promises handle asynchronous operations more cleanly than callbacks.
 - A Promise has three states: pending, fulfilled, and rejected.
 - Use 
.then()for success,.catch()for errors, and.finally()to run code regardless of outcome. - Promises can be chained to run multiple sequential async operations.