Node.js Async Patterns
Handling asynchronous operations
Callbacks
fs.readFile('file.txt', (err, data) => { # callback pattern
if (err) throw err;
console.log(data);
});
Promises
const promise = new Promise((resolve, reject) => {
if (success) resolve(data);
else reject(error);
});
promise
.then(data => console.log(data))
.catch(err => console.error(err));
Async/Await
async function readFile() { # async function
try {
const data = await fs.promises.readFile('file.txt');
console.log(data);
} catch (err) {
console.error(err);
}
}
Promise.all
const results = await Promise.all([ # parallel execution
fetchUser(),
fetchPosts(),
fetchComments()
]);
Promise.race
const result = await Promise.race([ # first to complete
fetchFromAPI1(),
fetchFromAPI2()
]);
Error Handling
process.on('unhandledRejection', (err) => { # catch unhandled rejections
console.error(err);
process.exit(1);
});