Promises in Node.js
Learn Promises for cleaner async code. Chain operations and handle errors elegantly.
Promises in Node.js
Promises are a cleaner way to handle async operations than callbacks.
Promise States
``` Pending → Fulfilled (resolved) → Rejected (error) ```
Creating a Promise
```javascript const myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve('It worked!'); } else { reject(new Error('It failed!')); } }); ```
Using Promises
```javascript myPromise .then(result => { console.log(result); // 'It worked!' }) .catch(error => { console.error(error.message); }); ```
Chaining Promises
```javascript function step1() { return new Promise(resolve => { setTimeout(() => resolve('Step 1 done'), 100); }); }
function step2(prev) { return new Promise(resolve => { setTimeout(() => resolve(prev + ' → Step 2 done'), 100); }); }
function step3(prev) { return new Promise(resolve => { setTimeout(() => resolve(prev + ' → Step 3 done'), 100); }); }
step1() .then(step2) .then(step3) .then(result => console.log(result)); // Step 1 done → Step 2 done → Step 3 done ```
Promise.all - Run in Parallel
```javascript const promise1 = fetch('/api/users'); const promise2 = fetch('/api/posts'); const promise3 = fetch('/api/comments');
Promise.all([promise1, promise2, promise3]) .then(([users, posts, comments]) => { console.log('All done!', users, posts, comments); }) .catch(error => { // If ANY promise fails, catch runs console.error('One failed:', error); }); ```
Promise.allSettled - Get All Results
```javascript Promise.allSettled([promise1, promise2, promise3]) .then(results => { results.forEach(result => { if (result.status === 'fulfilled') { console.log('Success:', result.value); } else { console.log('Failed:', result.reason); } }); }); ```
Promise.race - First One Wins
```javascript Promise.race([promise1, promise2, promise3]) .then(winner => { console.log('First to finish:', winner); }); ```
Converting Callbacks to Promises
```javascript const fs = require('fs');
function readFilePromise(path) { return new Promise((resolve, reject) => { fs.readFile(path, 'utf8', (err, data) => { if (err) reject(err); else resolve(data); }); }); }
// Or use util.promisify const { promisify } = require('util'); const readFile = promisify(fs.readFile); ```
fs.promises (Built-in)
```javascript const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8') .then(data => console.log(data)) .catch(err => console.error(err)); ```
Error Handling
```javascript // Always add .catch() at the end fetchData() .then(process) .then(save) .catch(error => { // Catches errors from any step console.error('Error:', error.message); }) .finally(() => { // Always runs console.log('Cleanup done'); }); ```
Key Takeaway
Promises make async code readable. Chain with `.then()`, catch errors with `.catch()`, run parallel with `Promise.all()`. Most Node.js APIs now have promise versions. Use them!