Async/Await for Asynchronous Operations

With the introduction of async/await in Node.js, handling asynchronous operations has become more readable and maintainable compared to traditional callback-based methods.

javascriptCopy code// Example using async/await
const fs = require('fs').promises;

async function readFile(filePath) {
    try {
        const data = await fs.readFile(filePath, 'utf8');
        console.log(data);
    } catch (err) {
        console.error('Error reading file:', err);
    }
}

readFile('./example.txt');

Explanation:

  • fs.promises provides promise-based versions of filesystem methods.
  • async/await is used to handle the asynchronous readFile method more cleanly.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *