Promises
Promises
Section titled “Promises”What it is
Section titled “What it is”Promises represent the eventual completion (or failure) of an asynchronous operation. Introduced in ES6 (2015), they provide a cleaner alternative to callback-based asynchronous code.
Before this feature
Section titled “Before this feature”Callbacks led to “callback hell” with nested functions:
// Callback hellgetData(function(a) { getMoreData(a, function(b) { getEvenMoreData(b, function(c) { console.log("Final result:", c); }, function(err) { console.error(err); }); }, function(err) { console.error(err); });}, function(err) { console.error(err);});After this feature
Section titled “After this feature”Promises enable chaining and cleaner error handling:
// Promise chaininggetData() .then(a => getMoreData(a)) .then(b => getEvenMoreData(b)) .then(c => console.log("Final result:", c)) .catch(err => console.error(err));
// Creating a Promiseconst fetchUser = (id) => { return new Promise((resolve, reject) => { setTimeout(() => { if (id > 0) { resolve({ id, name: "Alice" }); } else { reject(new Error("Invalid ID")); } }, 1000); });};
// Using the PromisefetchUser(1) .then(user => console.log(user)) .catch(err => console.error(err));
// Promise.all - run multiple promises in parallelconst promises = [ fetch("/api/users"), fetch("/api/posts"), fetch("/api/comments")];
Promise.all(promises) .then(results => console.log("All done:", results)) .catch(err => console.error("One failed:", err));
// Promise.race - use first to completePromise.race(promises) .then(result => console.log("First done:", result));Why this is better
Section titled “Why this is better”- Readable: Flat chain instead of nested callbacks
- Error handling: Single
.catch()handles all errors in chain - Composable: Easy to combine multiple async operations
- State: Promises have three states (pending, fulfilled, rejected)
- Guaranteed:
.then()always called asynchronously
Key notes / edge cases
Section titled “Key notes / edge cases”- A promise can only be resolved or rejected once
.then()returns a new promise, enabling chaining- Errors in
.then()are caught by subsequent.catch() - Unhandled promise rejections can crash Node.js apps
Promise.all()fails if any promise rejects- Use
Promise.allSettled()if you want all results regardless of failures
// Promise.allSettled - get all results (ES2020)Promise.allSettled([ Promise.resolve(1), Promise.reject("error"), Promise.resolve(3)]).then(results => { console.log(results); // [ // { status: 'fulfilled', value: 1 }, // { status: 'rejected', reason: 'error' }, // { status: 'fulfilled', value: 3 } // ]});Quick practice
Section titled “Quick practice”-
Create a promise that resolves with “Success” after 2 seconds.
Answer
const promise = new Promise((resolve) => {setTimeout(() => resolve("Success"), 2000);}); -
What’s the difference between
Promise.all()andPromise.race()?Answer
`Promise.all()` waits for all promises to resolve (or one to reject). `Promise.race()` resolves/rejects as soon as the first promise settles. -
How do you convert a callback-based function to use Promises?
Answer
function callbackFn(arg, callback) { /* ... */ }function promiseFn(arg) {return new Promise((resolve, reject) => {callbackFn(arg, (err, result) => {if (err) reject(err);else resolve(result);});});}