Async/await is a feature of JavaScript that allows developers to write asynchronous code in a more synchronous-looking way. With async/await, developers can write code that waits for an asynchronous operation to complete, without blocking the main thread of execution.
In this article, we’ll explore how to use async/await in JavaScript with some examples.
Syntax of Async/Await
The syntax of async/await is fairly simple. To define an asynchronous function, you add the async keyword before the function keyword, like this:
1 2 3 | async function getData() { // async code goes here } |
Inside the async function, you can use the await keyword to wait for a Promise to resolve, like this:
1 2 3 4 5 | async function getData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; } |
In this example, we use the fetch function to make an HTTP request, and then use the await keyword to wait for the response to be returned. We then use the await keyword again to wait for the JSON data to be parsed before returning it.
Example: Fetching data from an API using Async/Await
Let’s take a closer look at how to use async/await to fetch data from an API. In this example, we’ll use the fetch function to make an HTTP request to the GitHub API, and then use async/await to wait for the response to be returned.
1 2 3 4 5 6 7 8 9 10 | async function fetchGithubUser(username) { const url = `https://api.github.com/users/${username}`; const response = await fetch(url); const data = await response.json(); return data; } fetchGithubUser('octocat') .then(data => console.log(data)) .catch(error => console.error(error)); |
In this example, we define an async function called fetchGithubUser that takes a GitHub username as its parameter. Inside the function, we construct the URL for the API request, use the fetch function to make the request, and then use the await keyword to wait for the response to be returned. We then use the await keyword again to wait for the JSON data to be parsed before returning it.
To call the async function, we use the standard Promise syntax, with a .then()
method to handle the success case and a .catch()
method to handle any errors.
Example: Using Promises with Async/Await
Sometimes, you may need to use Promises with async/await. In this example, we’ll use the Promise.all()
method to make multiple API requests in parallel, and then use async/await to wait for all of the requests to complete before continuing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | async function fetchGithubData() { const urls = [ 'https://api.github.com/users/octocat', 'https://api.github.com/users/mojombo', 'https://api.github.com/users/defunkt' ]; const promises = urls.map(url => fetch(url)); const responses = await Promise.all(promises); const data = await Promise.all(responses.map(response => response.json())); return data; } fetchGithubData() .then(data => console.log(data)) .catch(error => console.error(error)); |
In this example, we define an async function called fetchGithubData that constructs an array of API request URLs and then uses the map()
method to create an array of Promises that will fetch the data from each URL. We then use the Promise.all()
method to wait for all of the requests to complete before continuing.
After we have received all of the responses, we use the map()
method again to create an array of Promises that will parse the JSON data from each response. We then use the await keyword again to wait for all of these Promises to complete before returning the data as an array of objects.
Best Practices for Using Async/Await
Here are some best practices for using async/await in your JavaScript code:
- Always handle errors: Asynchronous code can be prone to errors, so it’s important to always handle them properly. You can use try/catch blocks to catch errors within an async function, or you can use the
.catch()
method on a Promise to handle errors in the calling code. - Don’t overuse async/await: While async/await can make asynchronous code easier to read and write, it’s not always necessary or appropriate. Only use async/await when you need to wait for a Promise to resolve before continuing.
- Use Promise.all() for parallel requests: If you need to make multiple API requests in parallel, use the
Promise.all()
method to wait for all of the requests to complete before continuing. - Don’t block the main thread: Remember that asynchronous code is meant to run in the background, so avoid blocking the main thread of execution. If your code takes a long time to run, consider using a web worker to run it in the background.
- Keep functions small and focused: As with any function, it’s important to keep async functions small and focused. If a function is doing too much, consider breaking it up into smaller, more focused functions.
Conclusion
Async/await is a powerful feature of JavaScript that can make asynchronous code easier to read and write. By using the await keyword to wait for Promises to resolve, you can write code that looks and feels more like synchronous code. Just remember to handle errors properly, use Promise.all() for parallel requests, and avoid blocking the main thread of execution.