By the end of this lesson, you will understand how to use async and await in JavaScript to simplify asynchronous programming.
Async and await are features in JavaScript that simplify the way we handle asynchronous code. They allow you to write code that looks more like synchronous code, which makes it easier to read. For example, when waiting for a friend, you can tidy your room instead. Similarly, these tools let you handle tasks in parallel, reducing complexity.
File: async-await-example.js
async function fetchData() {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data = await response.json();
console.log(data);
}
fetchData();
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit
suscipit..."
}
The code above shows how to use the async function keyword. This marks the function as asynchronous. The await keyword pauses execution until a promise resolves. First, it waits for the fetch request to finish, and then it processes the JSON data. This approach makes it easier to deal with responses one after the other without complex chains. Therefore, using async programming can greatly improve your coding workflow.
Now it’s your turn! Create a function that fetches data from a different URL and logs the result. For instance, you can use the JSON placeholder API to get a list of users. This exercise will help you practice using asynchronous features in a real-world scenario.
async function fetchUsers() {
let response = await fetch('https://jsonplaceholder.typicode.com/users');
let users = await response.json();
console.log(users);
}
fetchUsers();
async, the await keyword won’t work. Always include async before the function definition.