Fetching API -- JavaScript Tutorial

pakgamer(63)
Published in
GEMS
Words
231
Reading
2 min
Listen
Play
6y

Hello Everyone

In the last post, we have discussed JavaScript local storage which is also a very important topic in learning JavaScript. If you haven't read that tutorial please read it because it will help you in the future. In this post, we are going to learn how can we fetch API. This is gonna be a simple tutorial. As we are going to learn about promises in the upcoming post so this tutorial will give you idea about what promises is and what exactly they do. So let me start directly with the visual studio.

erer.png

So here I have an HTML file open in my visual studio

image.png

And this fetchAPI.js file is linked to it.
image.png

so whatever I write here is executed.

image.png

async function fetchAPI(){
    const response= await fetch('https://api.github.com/users')
    const conJSON=response.json();
    return conJSON;
   }
   
   let obj= fetchAPI();
   obj.then(data=> console.log(data));

Here I am fetching data from a GitHub API which returns some data of users. Here I am using async/await function. First I have a function with fetch API name. The async function actually. Then I have a variable with name response which is using await. Then a conJson which is returning the response as JSON. and then I am returning that conJSON variable.

ok now let's try another API (fake API.)

image.png

async function fetchAPI(){
    const response= await fetch('https://jsonplaceholder.typicode.com/todos/1')
    const conJSON=response.json();
    return conJSON;
   }
   
   let obj= fetchAPI();
   obj.then(data=> console.log(data));

image.png

so as you can see it is working fine.

I think this much is enough for today. Now if you like the post please upvote and comment if you want to give me some advise
ntitled-1.png

Fetching API -- JavaScript Tutorial | Ecency