What the Fetch ()

Seyi Kanagui
3 min readOct 20, 2020

Requesting resources from an API is very common practice and an important feature needed for building modern applications. Whether you’re using your own API or a third-party API, you need a method to make those data requests without slowing your application down. The Fetch API is a very popular tool for speeding up these requests.

Fetch is a browser API for loading structured data, images, and text, asynchronously to update an HTML page. Fetch is built on the promise object which greatly simplifies the code.

The Fetch API provides a fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise(.then) that you can use to retrieve the response of the request.

Fetch API is a built-in Javascript ES6 Promise that is used to make XMLHttp Request simpler and easier to use the most common HTTP requests (GET, POST, PATCH, etc.) data asynchronously.

Asynchronous

Put simply, synchronous code is executed in sequence — each statement relies for the previous statement to finish before executing the next line of code. Asynchronous code doesn’t have to wait — your program can continue to run. You do this to keep your site or app responsive, reducing waiting time and creating a better user experience.

USING FETCH()

Calling fetch()method returns a promise. We then wait for the promise to resolve by passing a handler with the .then() method of the promise. That handler receives the return value of the fetch promise, a response object. If the request fails due to some network problems, the promise is rejected.

The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object (used heavily in AJAX programming.

The basic syntax of a fetch() method request(lines7–9):

Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch() takes one argument -the path to the resource you want to fetch-and returns a promise containing the response (a response object). This is only an HTTP response not the actual JSON. We need to extract the JSON body content from the response using the json() method. When called, this is the return we see in our console:

Resources:

--

--

Seyi Kanagui

Full-Time Software Engineering Student at Flatiron School, avid golfer, and wannabe chef.