SyntaxStudy
Sign Up
Node.js async/await and Error Handling
Node.js Beginner 10 min read

async/await and Error Handling

async/await is syntactic sugar over Promises that makes async code look and behave like synchronous code. An async function always returns a Promise. Use await inside it to pause execution until a Promise resolves. Wrap in try/catch for error handling.

Example
const fs = require('fs/promises');

// Basic async/await:
async function processFile(inputPath, outputPath) {
    try {
        const data = await fs.readFile(inputPath, 'utf8');
        const processed = data.toUpperCase();
        await fs.writeFile(outputPath, processed, 'utf8');
        console.log('File processed successfully.');
        return processed;
    } catch (err) {
        // Handle both read and write errors in one place:
        console.error('Error processing file:', err.message);
        throw err; // Re-throw so callers know it failed
    }
}

// Parallel execution with async/await:
async function fetchAllData() {
    const [users, products] = await Promise.all([
        fs.readFile('users.json', 'utf8'),
        fs.readFile('products.json', 'utf8'),
    ]);
    return {
        users:    JSON.parse(users),
        products: JSON.parse(products),
    };
}

// Promise.allSettled — don't fail if one rejects:
async function tryAll(paths) {
    const results = await Promise.allSettled(
        paths.map(p => fs.readFile(p, 'utf8'))
    );
    results.forEach((result, i) => {
        if (result.status === 'fulfilled') {
            console.log(`File ${i}: ${result.value.length} chars`);
        } else {
            console.warn(`File ${i} failed: ${result.reason.message}`);
        }
    });
}

processFile('input.txt', 'output.txt');