Js Promises in JavaScript
? JavaScript Promises
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Why Use Promises?
Before Promises, handling async tasks like network requests or timers led to "callback hell"—deeply nested callbacks hard to manage.
Promises allow you to write cleaner, more manageable asynchronous code.
Promise States
Pending: Initial state, operation not completed yet.
Fulfilled: Operation completed successfully.
Rejected: Operation failed.
Creating a Promise
const myPromise = new Promise((resolve, reject) => { // async operation let success = true; // simulate outcome if (success) { resolve("Operation succeeded!"); } else { reject("Operation failed!"); }});Using Promises: .then() and .catch()
myPromise .then(result => { console.log(result); // "Operation succeeded!" }) .catch(error => { console.error(error); // If rejected, logs error message });Example: Simple Promise with setTimeout
function wait(ms) { return new Promise((resolve) => { setTimeout(() => { resolve(`Waited for ${ms} milliseconds`); }, ms); });}wait(2000).then(message => console.log(message));Chaining Promises
You can chain multiple .then() calls to run sequential async operations:
wait(1000) .then(msg => { console.log(msg); return wait(2000); }) .then(msg => console.log(msg));Promise.all()
Wait for multiple promises to resolve in parallel:
Promise.all([wait(1000), wait(2000), wait(1500)]).then(messages => { console.log(messages);});Summary
| Term | Description |
|---|---|
| Promise | Represents future completion of async |
resolve() | Called when operation succeeds |
reject() | Called when operation fails |
.then() | Handles success |
.catch() | Handles error |
.finally() | Runs code regardless of success/failure |
Want me to explain async/await which is syntactic sugar over Promises?