codequick-darkmode-logo
Iniciar sesiónRegistrarse
  • javascript-advance

Using then and catch in JavaScript Promises

JavaScript Promises are used to handle asynchronous operations in a more organized and readable way. In a Promise chain, you can use the then and catch methods to handle the resolved and rejected states respectively.

The then method is used to specify what to do when a Promise is resolved. It takes a callback function as an argument, which will be called with the resolved value of the Promise. Here's an example:

fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error));

In this example, we're fetching data from an API using the fetch function. The first then method is used to convert the response to JSON format, and the second then method is used to log the data to the console.

The catch method is used to specify what to do when a Promise is rejected. It also takes a callback function as an argument, which will be called with the rejected reason of the Promise. This is useful for handling errors and displaying appropriate error messages. Here's an example:

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

In this example, if the fetch request fails or the response cannot be converted to JSON, the catch method will be called, and the error message will be logged to the console.

It's important to note that the then and catch methods return a new Promise, allowing you to chain additional then or catch methods to handle further asynchronous operations. This allows for a more sequential and readable code flow.

For more information and detailed examples, you can refer to the following resources: