Sobes.tech
Junior — Middle

What are the ways to handle asynchronous tasks in programming?

sobes.tech AI

Answer from AI

In Node.js, several main approaches are used for handling asynchronous tasks:

  1. Callbacks — the traditional method, where a function is passed as an argument and called after the operation completes.

  2. Promises — objects representing the result of an asynchronous operation, allowing code to be written with .then() and .catch() chains.

  3. async/await — syntactic sugar over promises, enabling writing asynchronous code in a synchronous style, simplifying reading and error handling.

  4. Event Emitters — for event-driven handling of asynchronous events.

Example with async/await:

async function fetchData() {
  try {
    const data = await someAsyncOperation();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}