Loading lesson path
Promises in Node.js provide a cleaner way to handle asynchronous operations compared to traditional callbacks. Promises represent the completion (or failure) of an asynchronous operation and its result.
: Initial state, operation not completed
: Operation completed successfully
: Operation failed Once a promise is settled (either fulfilled or rejected), its state cannot change.
With Callbacks getUser(id, (err, user) => {
if (err) return handleError(err);
getOrders(user.id, (err, orders) => {
if (err) return handleError(err);// Process orders...
});
});
With Promises getUser(id).then(user => getOrders(user.id)).then(orders => processOrders(orders)).catch(handleError);Flatter code structure (avoids callback hell) Better error handling with single.catch()
Callback Hell Example (Without Promises)
fs.readFile('file1.txt', (err, data1) => {
if (err) throw err;
fs.readFile('file2.txt', (err, data2) => {
if (err) throw err;
fs.readFile('file3.txt', (err, data3) => {
if (err) throw err;// Use data1, data2, and data3
});
});
});Promise constructor, which accepts an executor function with two parameters: resolve and reject.
// Create a new Promise const myPromise = new Promise((resolve, reject) => {
// Simulate an async operation (e.g., API call, file read)
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve('Operation completed successfully');
} else {
reject(new Error('Operation failed'));
}
}, 1000); // Simulate delay
});
// Using the Promise myPromise.then(result => console.log('Success:', result)).catch(error => console.error('Error:', error.message));Example: Reading a File with Promises const fs = require('fs').promises;
const promise1 = Promise.resolve('First result');
const promise2 = new Promise((resolve) => setTimeout(() => resolve('Second result'), 1000));
const promise3 = fs.readFile('myfile.txt', 'utf8'); // Read local file instead of fetch
Promise.all([promise1, promise2, promise3]).then(results => {
console.log('Results:', results);
// results[0] is from promise1
// results[1] is from promise2
// results[2] is the content of myfile.txt
}).catch(error => {
console.error('Error in one of the promises:', error);
});Promises can be chained to execute asynchronous operations in sequence, with each.then() receiving the result of the previous operation.
Example: Promise Chaining function getUser(userId) {
return new Promise((resolve, reject) => {
// Simulating database call setTimeout(() => {
resolve({ id: userId, name: 'John' });
}, 1000);
});
}
function getUserPosts(user) {
return new Promise((resolve, reject) => {
// Simulating API call setTimeout(() => {
resolve(['Post 1', 'Post 2', 'Post 3']);
}, 1000);
});
}
// Chain the promises getUser(123).then(user => {
console.log('User:', user);
return getUserPosts(user);
}).then(posts => {
console.log('Posts:', posts);
}).catch(error => {
console.error('Error:', error);
});Instance Methods then(onFulfilled, onRejected)
Promise.all(iterable)
Promise.race(iterable)
Promise.allSettled(iterable)
Promise.resolve(value)
Promise.reject(reason)
Promise.then()