Node.js — Async Programming
Callbacks
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
Promises
const readFile = (path) => {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
};
readFile('file.txt')
.then(data => console.log(data))
.catch(err => console.error(err));
Async/Await
async function getData() {
try {
const data = await readFile('file.txt');
console.log(data);
} catch (err) {
console.error(err);
}
}
Promise.all
const results = await Promise.all([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
]);
Promise.race
const result = await Promise.race([
fetch('/api/fast'),
fetch('/api/slow')
]);
Mini Practice
- Convert callbacks to promises
- Use async/await
- Parallel execution with Promise.all
- Handle multiple promises
Up Next
Continue with Callbacks — callback patterns.
Related Topics
Frequently Asked Questions about Async Programming
What is Async Programming in Node.js?
Async Programming 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 Async Programming?
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 Async Programming.
Why is Async Programming important in Node.js?
Async Programming is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.