Async/Await Handling Asynchronous Processes
async
and await
are syntactic features in JavaScript that help manage asynchronous processes in a straightforward and clean manner.
When using Promises, repeatedly chaining callbacks with .then()
and .catch()
can make the code complex and difficult to read.
async/await
resolves this issue, allowing you to write asynchronous code that resembles synchronous code.
This type of asynchronous handling is typically used when retrieving data from external servers or storage, as these tasks can be time-consuming.
For reference, interfaces used when fetching or sending data to servers are known as APIs.
API stands for Application Programming Interface
, denoting the set of rules for server communication.
async function fetchUserData() {
try {
// Using the fetch function to retrieve data from an external API
const response = await fetch('https://api.example.com/user');
// Parsing response as JSON
const data = await response.json();
// Logging the data
console.log(data);
} catch (error) {
console.error('Failed to fetch data:', error);
}
}
// Function call
fetchUserData();
In the above example, async
declares an asynchronous function, and await
waits for and then returns the result of the Promise.
If there is an issue with the fetch
call or data parsing, the catch
block handles the error.
Characteristics
-
Asynchronous Function: Declaring a function with
async
ensures the function always returns a Promise. -
Error Handling: Errors can be handled conveniently using a
try/catch
block.
Food Order Example
You can illustrate the async/await
pattern using a food ordering scenario.
-
async
represents the function that takes orders. -
await
waits for the food (Promise) to be prepared in async. -
try
signifies the scenario where the food is served and eaten. -
catch
denotes the scenario where the food isn't served.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.