Какие способы знаешь для организации асинхронного выполнения в JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, several main methods are used to organize asynchronous execution:
-
Callback functions — the classic way, where a function is passed to another function and called after the asynchronous operation completes.
-
Promises — an object representing the result of an asynchronous operation, which can be in a pending, fulfilled, or rejected state. They allow writing more readable code than nested callbacks.
-
async/await — syntactic sugar over promises, enabling writing asynchronous code in a synchronous style using the
asyncandawaitkeywords. -
Event Loop and microtasks — understanding the event loop helps organize asynchronous operations correctly.
-
Web Workers — for executing heavy tasks in the background thread, without blocking the main UI thread.
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();