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:
-
Callbacks — the traditional method, where a function is passed as an argument and called after the operation completes.
-
Promises — objects representing the result of an asynchronous operation, allowing code to be written with
.then()and.catch()chains. -
async/await — syntactic sugar over promises, enabling writing asynchronous code in a synchronous style, simplifying reading and error handling.
-
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);
}
}