Async/Await Asynchronous Handling
async and await are syntax features in JavaScript that make asynchronous code easier and cleaner to manage.
Using promises with .then() and .catch() to continuously link callback functions can make the code complex and reduce readability.
async/await addresses these issues and allows you to write asynchronous code just like synchronous code.
Such asynchronous handling is commonly used when fetching data from external servers or storage, as these operations can be time-consuming.
An interface used for tasks such as retrieving data from or sending data to a server is known as an API.
API stands for Application Programming Interface, which refers to a set of rules for communication with a server.
async function fetchUserData() { try { // Fetch data from an external API using the fetch function const response = await fetch('https://api.example.com/user'); // Parse as JSON const data = await response.json(); // Output data console.log(data); } catch (error) { console.log('Failed to fetch data:', error); } } // Call function fetchUserData();
In the example above, async is a keyword that declares an asynchronous function, and await is a keyword that waits for a promise to resolve before returning the result.
If there is an issue with the fetch call or data parsing, the catch block handles the error.
Features
-
Asynchronous Function: When you declare a function with
async, it always returns a promise. -
Error Handling: Errors can be conveniently managed using
try/catchblocks.
Food Order Example
async/await can be used to illustrate waiting for food in a restaurant scenario.
-
asyncrepresents the act of taking an order as a function. -
awaitwaits for the food (Promise) to be ready in async. -
tryrepresents the scenario where the food is served, and you eat it. -
catchrepresents the scenario where the food is not served.
Which keyword is used in JavaScript to simplify writing asynchronous code?
callback
function
async/await
setTimeout
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help