Dung (Donny) Nguyen

Senior Software Engineer

Asynchronous Operations

In Node.js, asynchronous operations allow the handling of tasks that take time to complete, such as network requests, file system operations, or database queries, without blocking the main execution thread. Here’s an overview of the three primary ways to handle these asynchronous operations in Node.js: callbacks, promises, and async/await.

1. Callbacks

Definition: A callback is a function passed as an argument to another function, which is then executed once the asynchronous operation completes. This is one of the earliest approaches to handle asynchronous code in JavaScript.

Example:

const fs = require('fs');

fs.readFile('example.txt', 'utf-8', (err, data) => {
  if (err) {
    console.error("Error reading file:", err);
  } else {
    console.log("File content:", data);
  }
});

Pros:

Cons:

2. Promises

Definition: Promises provide a cleaner way to handle asynchronous operations and avoid callback hell. A promise represents a value that may be available now, in the future, or never. Promises have three states: pending, resolved (fulfilled), and rejected.

Example:

const fs = require('fs').promises;

fs.readFile('example.txt', 'utf-8')
  .then(data => {
    console.log("File content:", data);
  })
  .catch(err => {
    console.error("Error reading file:", err);
  });

Pros:

Cons:

3. Async/Await

Definition: async/await is syntactic sugar built on top of promises, introduced in ES2017. It makes asynchronous code look and behave more like synchronous code, using await to pause execution until a promise is resolved.

Example:

const fs = require('fs').promises;

async function readFile() {
  try {
    const data = await fs.readFile('example.txt', 'utf-8');
    console.log("File content:", data);
  } catch (err) {
    console.error("Error reading file:", err);
  }
}

readFile();

Pros:

Cons:

Summary

Choosing between these approaches depends on the complexity and structure of the asynchronous tasks we’re handling, with async/await typically preferred for its readability and ease of debugging.