Sobes.tech
Junior — Middle

What methods do you use to implement asynchronous operations in your code?

sobes.tech AI

Answer from AI

In Node.js, several approaches are commonly used to implement asynchronous operations:

  1. Callbacks — the classic method, where a function takes another function as an argument, which is called upon completion of the asynchronous operation.

  2. Promises — an object representing the result of an asynchronous operation, which can be in a pending, fulfilled, or rejected state. It allows writing more readable code, avoiding "callback hell".

  3. async/await — syntactic sugar over promises, enabling writing asynchronous code in a synchronous style, which improves readability and maintainability.

Example with async/await:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();
What methods do you use to implement asynchronous… - sobes.tech