How JavaScript Promises Work
In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an
asynchronous operation and its resulting value. Promises help in writing cleaner and more
manageable asynchronous code compared to callbacks.
1. States of a Promise
A Promise can be in one of three states:
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
2. Creating a Promise
A Promise is created using the Promise constructor, which takes a function with two arguments:
resolve and reject. const myPromise = new Promise((resolve, reject) => { let success = true;
if(success) { resolve("Operation successful!"); } else { reject("Operation failed."); } });
3. Consuming a Promise
Promises are consumed using .then(), .catch(), and .finally() methods. myPromise .then(result =>
console.log(result)) // Runs on success .catch(error => console.error(error)) // Runs on failure
.finally(() => console.log("Done"));
4. Promise Chaining
Multiple .then() calls can be chained to perform sequential asynchronous operations.
fetch("https://api.example.com/data") .then(response => response.json()) .then(data =>
console.log(data)) .catch(error => console.error(error));
5. Async/Await
Introduced in ES8, async/await makes working with Promises more readable. async function
fetchData() { try { let response = await fetch("https://api.example.com/data"); let data = await
response.json(); console.log(data); } catch(error) { console.error(error); } }
In summary, Promises in JavaScript are powerful tools for handling asynchronous operations. They
simplify working with asynchronous code and make it easier to manage errors and control flow.