Node.js — Promises
Creating Promises
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('It worked!');
} else {
reject('Something went wrong');
}
});
Consuming Promises
myPromise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log('Done'));
Chaining
fetchUser(1)
.then(user => fetchPosts(user.id))
.then(posts => renderPosts(posts))
.catch(err => handleError(err));
Promise.all
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts()
]);
Promise.allSettled
const results = await Promise.allSettled([
fetch('/api/fast'),
fetch('/api/slow')
]);
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log(result.value);
} else {
console.error(result.reason);
}
});
Promise.race
const result = await Promise.race([
fetch('/api/primary'),
fetch('/api/backup')
]);
Mini Practice
- Create a promise
- Chain promises
- Use Promise.all
- Handle rejection
Up Next
Continue with Async Await — modern async syntax.
Related Topics
Frequently Asked Questions about Promises
What is Promises in Node.js?
Promises is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Promises?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Promises.
Why is Promises important in Node.js?
Promises is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.