Junior
Tell us about the async/await construct in JavaScript.
sobes.tech AI
Answer from AI
async/await is syntactic sugar over promises, designed for easier writing of asynchronous code that looks synchronous.
A function marked with the async keyword always returns a promise. Inside an async function, you can use the await keyword.
The await operator is used before calling a promise. It pauses the execution of the async function until the promise is fulfilled (resolved) or rejected. The result of the promise (success value or error) is returned by the await operator.
If the promise before await is rejected, it throws an exception, which can be caught using a try...catch block.
// Example of using async/await
async function fetchData() {
try {
// Wait for an asynchronous operation to complete (e.g., an API request)
const response = await fetch('https://api.example.com/data');
// Parse the response as JSON
const data = await response.json();
// Log the received data
console.log(data);
} catch (error) {
// Catch any errors
console.error('Error fetching data:', error);
}
}
// Call the async function
fetchData();
// Example of an async function returning a promise
async function getValue() {
return 10; // This is automatically wrapped in Promise.resolve(10)
}
getValue().then(value => console.log(value)); // Will output 10
Advantages of async/await:
- Readability: Asynchronous code becomes more like synchronous code
- Error handling: Easier to use standard
try...catchblocks - Less nesting: Avoids "callback hell" or long chains of
.then().
Remember that await can only be used inside async functions.