Questions
What are Promises 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 need to find a way to handle the asynchronous nature of the API call.
The Challenge
Explain what Promises are in JavaScript and how you would use them to solve this problem. What are the different states of a Promise, and what are the key methods that you would use to interact with a Promise?
A junior engineer might try to solve this problem by using a callback. This would work, but it would not be a very robust solution. They might not be aware of Promises, which are the standard way to handle asynchronous operations in modern JavaScript.
A senior engineer would know that Promises are the perfect tool for this job. They would be able to explain what Promises are and how to use them to handle asynchronous operations.
Step 1: Understand What Promises Are
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Step 2: The Different States of a Promise
| State | Description |
|---|---|
pending | The initial state of a Promise. |
fulfilled | The state of a Promise that has been successfully resolved. |
rejected | The state of a Promise that has been rejected. |
Step 3: The Key Methods of a Promise
| Method | Description |
|---|---|
then() | Called when a Promise is fulfilled. |
catch() | Called when a Promise is rejected. |
finally() | Called when a Promise is settled (either fulfilled or rejected). |
Step 4: Solve the Problem
Here’s how we can use a Promise to make an API call:
fetch('https://api.example.com/my-data')
.then(response => response.json())
.then(data => {
// ... (update the UI with the data) ...
})
.catch(error => {
// ... (handle the error) ...
});In this example, the fetch() function returns a Promise that resolves with the response from the API. We then use the then() method to parse the response as JSON and to update the UI with the data. We use the catch() method to handle any errors that occur.
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?