Promises
Promises are a powerful tool for managing asynchronous operations in JavaScript. They represent a placeholder for the eventual result of an asynchronous operation. Here's an explanation of promises, promise chaining, promise composition, and promise error handling with code examples:
Promises:
A promise represents the eventual completion or failure of an asynchronous operation, and its eventual value. Promises have three states: pending, fulfilled, or rejected.
const myPromise = new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber < 0.5) {
resolve(randomNumber); // Fulfill the promise
} else {
reject(new Error('Random number is greater than 0.5')); // Reject the promise
}
}, 1000);
});
myPromise.then(
result => console.log('Success:', result), // Called when the promise is fulfilled
error => console.error('Error:', error) // Called when the promise is rejected
);
Promise Chaining:
Promise chaining allows you to chain multiple asynchronous operations together sequentially.
const firstPromise = new Promise(resolve => {
setTimeout(() => resolve(1), 1000);
});
const secondPromise = firstPromise.then(result => {
console.log('First result:', result);
return result * 2;
});
secondPromise.then(result => {
console.log('Second result:', result); // Output: Second result: 2
});
Promise Composition:
Promise composition allows you to perform multiple asynchronous operations in parallel and combine their results.
const fetchUserData = () => {
return new Promise(resolve => {
setTimeout(() => resolve({ username: 'user123' }), 1000);
});
};
const fetchUserPosts = () => {
return new Promise(resolve => {
setTimeout(() => resolve(['post1', 'post2']), 1500);
});
};
Promise.all([fetchUserData(), fetchUserPosts()]).then(([userData, userPosts]) => {
console.log('User data:', userData); // Output: User data: { username: 'user123' }
console.log('User posts:', userPosts); // Output: User posts: ['post1', 'post2']
});
Promise Error Handling:
You can handle errors in promises using the .catch()
method or by chaining a rejection handler using .then()
.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber < 0.5) {
resolve(randomNumber); // Fulfill the promise
} else {
reject(new Error('Random number is greater than 0.5')); // Reject the promise
}
}, 1000);
});
myPromise
.then(result => console.log('Success:', result))
.catch(error => console.error('Error:', error));
In this example, the .catch()
method is used to handle any errors that occur during the asynchronous operation.
Promises provide a cleaner and more manageable way to handle asynchronous operations in JavaScript, especially when dealing with multiple asynchronous tasks and complex error handling scenarios.
Leave a Comment