Questions
What are `async/await` and how do you use them in JavaScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new feature that needs to make an API call to get some data and then update the UI with the data.
You are using Promises to handle the asynchronous nature of the API call, but you find the code to be a bit verbose and difficult to read.
The Challenge
Explain what async/await is in JavaScript and how you would use it to solve this problem. What are the key benefits of using async/await over Promises?
A junior engineer might not be aware of `async/await`. They might just use Promises, which would work, but it would not be as readable as using `async/await`.
A senior engineer would know that `async/await` is the perfect tool for this job. They would be able to explain what `async/await` is and how to use it to write more readable and maintainable asynchronous code.
Step 1: Understand What async/await Is
async/await is a feature that was added in ES2017. It is syntactic sugar on top of Promises that makes asynchronous code look and behave more like synchronous code.
Step 2: The async and await Keywords
| Keyword | Description |
|---|---|
async | The async keyword is used to declare an asynchronous function. |
await | The await keyword is used to wait for a Promise to be resolved. |
Step 3: Solve the Problem
Here’s how we can use async/await to make an API call:
async function getData() {
try {
const response = await fetch('https://api.example.com/my-data');
const data = await response.json();
// ... (update the UI with the data) ...
} catch (error) {
// ... (handle the error) ...
}
}In this example, the await keyword is used to wait for the fetch() function to return a response and for the response.json() method to parse the response as JSON.
async/await vs. Promises
| Feature | Promises | async/await |
|---|---|---|
| Readability | Can be difficult to read, especially for complex asynchronous operations. | Very readable, makes asynchronous code look and behave like synchronous code. |
| Error Handling | Uses the .catch() method to handle errors. | Uses a try...catch block to handle errors. |
Practice Question
You want to make two API calls in parallel and then do something with the results of both calls. Which of the following would you use?