Fetch in JavaScript
ES6 includes the concept of Fetch, rather than using the XMLHttp Request Object in JavaScript. Fetch provides a cleaner interface for retrieving resources from internal and external sources. The interface seems familiar to XMLHttpRequest, but Fetch is more flexible and powerful.
In Simple form, Fetch is a method on the global object that takes a string. where the string contains the path of resources, that is going to retrieved.
fetch('path string');
‘then’ method is used to perform the fetch. ‘then’ method gets in a function callback with an optional parameter.
fetch('myUrl.com').then(response => {
console.log(response);
});
In above example, optional parameter is named as ‘response’. But it as anything that you want. The optional parameter contains an object that is returned from fetch object. The most commonly used properties of the response object are as follow:
Status: It contains status code from HTTP call which is represented as an integer.
statusText: It is a status code represented as a string. For example: statusText is “Ok” which is equivalent to status code value 200.
ok: It is a Boolean value and is an easy way to check if the status code returned from the request is in the range of 200-299.
Here we can see fetch request and its response object in example below:
fetch('https://api.github.com').then(response => {
console.log(response);
});
We can see result in browser console. Where, we can see ok:true, status:200, statusText: “OK”.
Reference:
1.MDN Web Docs. (2018). Fetch API. [online] Available at: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API [Accessed 22 Oct. 2018].
2.Constructcode.com. (2018). Introduction to Fetch in JavaScript - Construct Code. [online] Available at: https://www.constructcode.com/post/introduction-to-fetch-in-javascript [Accessed 20 Oct. 2018].