Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
fetch
asynchronous
communitycreator

What is fetch() in JavaScript?

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In JavaScript, the fetch() method is used to make asynchronous requests to the server and load the information that is returned by the server onto the web pages.

Syntax

fetch(URL, options);

Parameters

The fetch() method accepts the following two parameters.

  • URL: The URL on which the request is to be made.
  • Options: An object which consists of additional properties that can be sent to the server. It is optional.

Return value

The fetch() method returns a promise that can either be resolved or not. Thus, this method always returns a value and the only possible case where it may fail to return anything is a server error.

Code

Let’s make some requests to a public URL and see how fetch works in detail.

Console

The fetch method works in a chain of multiple then() methods and one error() method. The error() method will only be called if any error occurs while the request is made.

The format of returned data can be JSON or XML. Here, we have explicitly converted the returned data to JSON format using json() method and logged it into the console. Thus, we can get any data we want from the server via fetch().

The default method of fetch() is GET. If needed, we can also make a POST, PUT and DELETE method request as well. Below is an example of fetch() using the POST method.

Console

RELATED TAGS

javascript
fetch
asynchronous
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring