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:
-
Callbacks — the classic method, where a function takes another function as an argument, which is called upon completion of the asynchronous operation.
-
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".
-
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();