Fetch API

Asynchronous Programming in JavaScript offers a great way of handling various input and output operations that are not immediately executed. These don't provide immediate response.

One of the example where the response is not immediate is getting data from a server through Application ProgrammingInterface(API).Whenever we make a call to server through an API to get us data, the data is not received immediately. JavaScript works in synchronous manner so it will not wait for the response to come back and execute the code after the request. This can cause error as we might have code that depends on the data received from the request.

Now we will discuss fetch API which can help us to deal with this situation.

fetch() ,the fetch API is a new built-in way to make API requests. It a new standard to make server requests with promises to HTTP.

It is similar to XMLHttpRequest(XHR) but is better in many ways. It uses Promises, which enables a cleaner, more concise syntax , no need to remember the complex structure of XMLHttpRequest and avoid callback hell.

The fetch API provides the fetch() method under the window object that means we can directly start using fetch.

It returns a Promise that can we used to retrieve the response of the request.

Basic Fetch Syntax

fetch(url)

the URL parameter is mandatory parameter. After this we include the promise method then()

.then(function(response) {         
  })

the fetch method returns a promise. Now if the promise returned is resolved, then the then() block is called. If the promise is not resolved, the the catch() method is called.

.catch(function(error){
});

So the fetch request can be written as

fetch(url)
.then(function(response){
})
.catch(function(error){
})

Loading our JSON Data

If we try to print the response from then to console, we would see that we recieve an object Promise which represents a result.But to get our JSON data, we have to chain another .then() method and parse the data through .json() method which return the response body as JSON. The reason for chaining another .then() method is that .json() method also returns a promise.

fetch(url)
.then(function(response){
   return response.json();
})
.then(function(response){
    console.log("JSON data" , response);
})
.catch(function(error){
    console.log("error",error);
})

This solves the problem faced while dealing with asynchronous calls. We can deal with the response independently

Sending POST Request

If we want to send a POST request to the API and supply some parameters in the body of the request. This can be done in the fetch() request:

var objData={}; //information to be passed 
fetch(url, {
    method:"post",
    headers:{} //if we want to add any new headers
    body: JSON.stringify(objData)
    })
.then(function(response){
     return response.json();
})
.then(function(response){
      console.log("Data ",response);
})
.catch(function(error){
      console.log("Request Failed", error);
});

In this article, we have seen how the fetch API works and solve our problem. We have seen how to retrieve the data with the fetch() method, how to handle errors and how to handle post request with fetch.I hope that this article helped you to understand fetch a little better.

Happy Coding!