Shriram Navaratnalingam
Loops Blog
Published in
3 min readMar 12, 2019

--

Now we going have a look into JavaScript Fetch API From Scratch. If you have a pretty basic knowledge of JavaScript then you’re good to go. As the name defines the Fetch API facilitates an interface which is used to fetch resources . If you have already performed such a requesting functionality you may remember the dreaded XMLHttpRequest which is basically a block of messy code, it didn’t have promises and to be honest, it wasn’t all JavaScript.

In another way if you were using jQuery, then it’s pretty cleaner syntax with jQuery.ajax().

But Now, JavaScript has it is own built-in neat way to do this operation.And that is what we going to look today “JavaScript Fetch API

The fetch() network requests are very much similar to that of XMLHttpRequest . What makes it different is that Fetch API uses Promises, which makes it more simpler and easier API.In another way Promise also avoids callback hell. In the ES7, there was a feature called async-await was introduced which allow us to eliminate promise and work as a plain JavaScript function, but the promise is the most convenient way of sending request for a response to be received.

Fetch Request

Basically as we request a call fetch with the URL, by default the Fetch API makes the request as a GET method. Following code snippet shows how such direct call is made.

Here, the response we received is not JSON but a simple Javascript object with set of methods that can be used to process our data further.

Getting the JSON response

Here when the HTTP request finished processing, we receive a promise with data, and then we resolve response object with the json() a method exposed by response object itself.

Since json() also returns a promise, we need to chain that as well to another then(), before we log the JSON response into the console.

Async /Await with Fetch call

Async/await feature to deal with Promises and function chaining instead of callbacks

Async function means : It always return a Promise, even if function actually returns a non-promise value(integer),
async keyword direct JS to wrap the value as "resolved" Promise

To check whether Promise is resolved - then() is used


asyn function foo(){
return 1;
}

foo().then(alert);

await function enables the JavaScript to wait till the promise is resolved and returns the response.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Very very important !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
We will get syntax error - if we do not put "async" before a function and use await, await only works inside an async function.

This bring a conclusion to the learning of Git basic flow!!!

Thanks for reading my blog….See you soon in the next blog

--

--