Junior
What are async/await and what are they used for?
sobes.tech AI
Answer from AI
Async/await is syntactic sugar over promises in JavaScript, allowing you to write asynchronous code in a synchronous style.
They are needed for:
- Improving code readability: Asynchronous code becomes more sequential and understandable, avoiding "callback hell".
- Simplifying error handling:
try...catchblocks work with async/await just like with synchronous code. - Easier debugging: The flow of execution is more apparent.
Key points:
- A function marked with
asyncalways returns a promise. - The
awaitoperator can only be used inside anasyncfunction. It pauses the execution of theasyncfunction until the promise it is applied to is fulfilled or rejected, then returns the result or throws an error.
// Example of using async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data'); // Wait for the fetch promise to resolve
const data = await response.json(); // Wait for the response.json() promise
console.log(data);
} catch (error) {
console.error('Error fetching data:', error); // Error handling
}
}
fetchData(); // Call the asynchronous function