Back to Freecodecamp

What Are Promises, and How Does Promise Chaining Work?

curriculum/challenges/english/blocks/lecture-understanding-asynchronous-programming/673407ca21117a67cf9521ca.md

latest4.1 KB
Original Source

--description--

A Promise is an object that represents the eventual completion or failure of an asynchronous operation. It's initially in a pending state. It can then transition to either a fulfilled state when the operation is successful, or a rejected state when the operation fails. Here's an example of creating a Promise:

js
const aPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Operation successful!");
  }, 1000);
});

In this example, we create a promise that simulates an asynchronous operation using setTimeout. After one second, the promise is resolved with the message Operation successful!.

Another way to work with promises is to use the .then and .catch methods.

The .then() method is used in a promise to specify what should happen when the promise is fulfilled, while .catch() is used to handle any errors that occur. Let's see how we can use .then and .catch with our promise:

js
aPromise.then((result) => {
  console.log(result);  // Outputs: "Operation successful!"
}).catch((error) => {
  console.error(error);
});

In this code, or instructions of what to do when the promise is fulfilled, the function passed to .then() will be called with the resolved value of the promise. If an error occurs, the function passed to .catch() will be called instead.

Now, let's talk about promise chaining. One of the powerful features of promises is that we can chain multiple asynchronous operations together. Each .then() can return a new promise, allowing you to perform a sequence of asynchronous operations one after the other. Here’s an example:

js
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    return fetch('https://api.example.com/data2');
  })
  .then(response => response.json())
  .then(data2 => console.log(data2))
  .catch(error => console.error('Error:', error));

In this example, we're making two API calls in sequence. The first .then() parses the response as JSON. The second .then() logs the data and makes another API call. The third .then() parses the response of the second API call, and the fourth .then() logs that data. If an error occurs at any point in this chain, it will be caught by the .catch() at the end.

It's important to note that .catch() will catch errors from any of the previous steps in the chain. This means you don't need to add error handling to each individual step, which can greatly simplify your code.

--questions--

--text--

What are the possible states of a Promise?

--answers--

Active, Inactive, or Terminated.

--feedback--

Think about the stages a Promise goes through from creation to completion.


Running, Paused, or Stopped.

--feedback--

Think about the stages a Promise goes through from creation to completion.


Pending, Fulfilled, or Rejected.


Started, Processing, or Ended.

--feedback--

Think about the stages a Promise goes through from creation to completion.

--video-solution--

3

--text--

What is the purpose of the .then() method in Promise chaining?

--answers--

To create a new Promise.

--feedback--

Consider what .then() allows you to do with the result of a Promise.


To specify what happens when a Promise is fulfilled.


To handle errors in the Promise chain.

--feedback--

Consider what .then() allows you to do with the result of a Promise.


To cancel a Promise.

--feedback--

Consider what .then() allows you to do with the result of a Promise.

--video-solution--

2

--text--

In a Promise chain, where should you typically place the .catch() method?

--answers--

After each .then().

--feedback--

Think about how .catch() can handle errors from multiple steps in the chain.


Before the first .then().

--feedback--

Think about how .catch() can handle errors from multiple steps in the chain.


In the middle of the chain.

--feedback--

Think about how .catch() can handle errors from multiple steps in the chain.


At the end of the chain.

--video-solution--

4