📜  fetch catch (1)

📅  最后修改于: 2023-12-03 15:15:03.188000             🧑  作者: Mango

Introduction to Fetch and Catch in JavaScript

Fetch

Fetch is a web API in JavaScript that allows you to make HTTP requests to a server and receive responses. It simplifies the process of sending and retrieving data from a server. The fetch API returns a promise which can be resolved with the response data from the server.

Here is an example of how to make a basic fetch request:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we are making a request to the JSONPlaceholder API and fetching a single to-do item. Once the promise is resolved, we are parsing the response data as JSON and logging it to the console. If the promise is rejected due to an error, we catch the error and log it to the console.

Fetch also allows you to modify and set options for your requests such as the HTTP method, headers, and body data.

Catch

Catch is a method that can be called on a rejected promise. It is used to handle errors that may occur during the execution of the promise.

Here is an example of how to use catch:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, if an error occurs during the fetch request, the promise will be rejected and the catch block will be executed. The error will be logged to the console.

Conclusion

Fetch and catch are important parts of JavaScript that allow you to make requests to servers and handle errors that may occur during the execution of those requests. By understanding how to use them, you can create efficient and reliable web applications.