Fetching API -- JavaScript Tutorial

in GEMS4 years ago

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

Sort:  

Amazing post on javascript tutorial. Your efforts are laudable. Your effort will be helpful for the around the globe to learn the skill of javascript. Keep it up your good work. I advise you to share the links of previous posts on new post. It will make easier to explore previous posts on same topic.

Your post has been curated with @gitplait community account because this is the kind of publications we like to see in our community.

Join our Community on Hive and Chat with us on Discord.

[Gitplait-Team]