</>
Skip to content
Node.js lessons (27/44)

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

  1. Convert callbacks to promises
  2. Use async/await
  3. Parallel execution with Promise.all
  4. 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.