Junior
Milliseid viise teate asünkroonse koodi töötamiseks?
sobes.tech AI
Vastus AI-lt
- Callback functions: Passing a function as an argument to another function, which will be called after the asynchronous operation completes. Can lead to "callback hell".
- Promises: Objects representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Provide more structured asynchronous control.
// Example of using a promise fetch('/api/data') .then(response => response.json()) // Handling successful response .then(data => console.log(data)) // Handling received data .catch(error => console.error('Error fetching data:', error)); // Handling error - Async/await: Syntactic sugar over promises, allowing writing asynchronous code in a more synchronous style, making it more readable and easier to debug.
// Example of using async/await async function fetchData() { try { const response = await fetch('/api/data'); // Waiting for promise to resolve if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); // Waiting for promise to resolve console.log(data); } catch (error) { console.error('Error fetching data:', error); // Handling error } } fetchData(); - Generators: Can be used for working with asynchronous code in conjunction with the
colibrary or manually, althoughasync/awaithas become more common.
Comparison of main approaches:
| Method | Advantages | Disadvantages |
|---|---|---|
| Callbacks | Simple at the initial stage | "Callback hell", error handling complexity |
| Promises | Improved readability, error handling | Can be bulky in chains of operations |
| Async/await | High readability, similar to synchronous code | Requires support of async/await environment |