📜  intro-to-promises fetch() - Javascript (1)

📅  最后修改于: 2023-12-03 14:42:08.538000             🧑  作者: Mango

Intro to Promises and Fetch() in JavaScript

Asynchronous programming in JavaScript can be accomplished using Promises and the Fetch API. Promises allow us to handle asynchronous tasks more efficiently by providing a way to handle the result of an asynchronous operation once it has completed. The Fetch API enables us to make HTTP requests to servers and retrieve data in a more modern way than traditional XMLHTTPRequest.

Promises

A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises have three states:

  1. Pending: the initial state
  2. Fulfilled: the operation completed successfully
  3. Rejected: the operation failed

Promises can be created using the new Promise() constructor and takes a single argument, which is a function that contains code that will do the asynchronous task. This function takes two arguments, resolve and reject, which are called depending on whether the operation is successful or not.

Example:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const result = 42;
    resolve(result);
  }, 1000);
});

myPromise.then((result) => {
  console.log(result); // 42
});

In the example above, we create a new Promise which will resolve to result after 1 second. Once the Promise resolves, we call .then() on it to handle the result.

Fetch API

The Fetch API is a modern way to make HTTP requests in JavaScript. It provides a more straightforward and streamlined way to work with HTTP requests than the traditional XMLHttpRequest object.

The Fetch API returns a Promise that resolves to the Response object of the HTTP request. The Response object contains the status of the request and any data that was retrieved.

Example:

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

In the example above, we make a HTTP GET request to retrieve a JSON object containing a todo item. The response is then parsed into JSON using the .json() method, and the resulting data is logged to the console.

Conclusion

Promises and Fetch API are powerful tools in modern JavaScript for handling asynchronous tasks and making HTTP requests. Understanding how to use them effectively can greatly enhance the functionality and efficiency of your JavaScript applications.