DEV Community

Beginners Guide To Fetching Data With (AJAX, Fetch API & Async/Await)

/[Abejide Femi Jr]\s/ on May 20, 2018

Introduction In this tutorial, I will be explaining how to fetch data asynchronously from an external API using web technologies like AJ...
Collapse
 
mpj profile image
Mattias Petter Johansson • Edited

Note that response.json() returns a PROMISE. This is a common misconception. This article is a wee bit misleading in the async / await example, the data variable will be a promise but the example sort of makes it seem like response.json() is sync by not using await in front of the call.

Collapse
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/

Thank you for spotting that out Mattias, it was a mistake, and the code as been edited.
Cheers.

Collapse
 
ronaldoperes profile image
Ronaldo Peres

What is a Promise?

Collapse
 
aglamadrid19 profile image
Alvaro Lamadrid • Edited
Collapse
 
itachiuchiha profile image
Itachi Uchiha • Edited

Is there a way extract data from promise? For example, I don't want to use like this:

blah().then()
Collapse
 
maccabee profile image
Maccabee

You can await Promises.

const data = await blah();

That's how async/await compile with babel, into Promises.

Collapse
 
itachiuchiha profile image
Itachi Uchiha

Thanks a lot. It worked :) Why I didn't try that. I think I was confused.

Collapse
 
pierrejoubert73 profile image
Pierre Joubert

Ah much better xD

Collapse
 
pierrejoubert73 profile image
Pierre Joubert

Do you not like the syntax? Or do you not want to deal with promises?

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I just wonder about assign result to a variable. I don't wan't to use then all time. For example:

const myResults = fetch('site.com')
   .then(resp => resp.json())
   .then(obj => obj)

console.log(myResults)
// { name: 'John', surname: 'Doe' }

Thread Thread
 
pierrejoubert73 profile image
Pierre Joubert • Edited

I just did this and it seemed to work:

var foo = null;
fetch('https://jsonplaceholder.typicode.com/posts/1')
   .then(resp => resp.json())
   .then(obj => foo = obj)

Then foo is accessible object like: foo.title
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit"

Thread Thread
 
itachiuchiha profile image
Itachi Uchiha

Thanks a lot. That's exactly what I want.

Collapse
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/

don't know of any, apart from .then(), and .catch() -> for errors.

Collapse
 
eripanci profile image
Eri Pançi

Great article. It inspired me to experiment with API's since I'm in a period of learning Javascript. But doing a small project I got a problem, and since I didn't find an article online, I thought to ask here, hope I'll be clear:
Is there a possibility to make the async function and getData in different functions or objects?

Because in your example both these are immediately after one another. But after some time my code gets messy, so I wanted to make the function and the call in different objects.

Thank you.

Collapse
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/

Hello, can you share your code

Collapse
 
eripanci profile image
Eri Pançi

since I'm working on Glitch, here is the full project: glitch.com/edit/#!/titanium-freeze

As you can see, inside the function getMovies it's async function and getData(). Can I make these two not inside one function but instead in two? One can get the data, the other can show it?

Thank you.

Thread Thread
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/ • Edited

Can't access that URL, can you paste your code here please, or possibly push to GitHub and send the URL

Thread Thread
 
eripanci profile image
Eri Pançi

Strange. Anyway here it is in Github: github.com/erip2/MovieApp/

Thread Thread
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/ • Edited

firstly, what are the datas you are trying to get from the API, i can also see you are trying to persist to sessionstorage, es6 classes could make the code look cleaner a bit tho, have a separate class for your ui, another class for you Session or local storage, then another class for the Movie.

Thread Thread
 
eripanci profile image
Eri Pançi

The data I'm getting from API is an array of movie titles the user search. Then when user clicks for details, I save the movie ID in sessionStorage to open a new window with that movie details.

That was exactly why I asked, to do these in different places in my code. Could I do these in different objects or should I read about JS classes since I don't know them very well to use it?

Thanks again.

Thread Thread
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/

sorry for the late reply, can you check this out github.com/abejide001/Github-profi....

Collapse
 
aloksdiptim profile image
alokz diptim!

Won't Ajax jquery be easier than this ?

Collapse
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/

with sound knowledge in vanilla JavaScript, you might not need jquery in your code, i prefer Ajax with vanilla JavaScript to Ajax with jquery.

Collapse
 
aloksdiptim profile image
alokz diptim!

Okay that is good

Collapse
 
maccabee profile image
Maccabee

jQuery is a very large library if you just want Ajax

Collapse
 
filxy1 profile image
filza • Edited

when i use fetch API I AM GETTING NOTHING ON MY LOCAL HOST

THIS IS MY CODE
var express = require("express");
var app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});

const fetch = require('node-fetch');
fetch('URL')
.then(res => res.json())//response type
.then(data => console.log(data));

Collapse
 
lewisyuburi profile image
Lew Yuburi

Can I translate this to spanish in my Medium blog? I will reference this post

Collapse
 
bjhaid_93 profile image
/[Abejide Femi Jr]\s/

You are free to do so.

Collapse
 
bgadrian profile image
Adrian B.G. • Edited

And while learning these, you may want to know they invented a new way of fetching a resource youtu.be/Wi_PhaFdjlo

Collapse
 
onuoha_ifeanyi profile image
Ifeanyi onuoha • Edited

Great article. It cleared me perfectly in a very brief and precise manner. Thanks

Collapse
 
anitabenites profile image
Ana María Benites Rodríguez

Nice, thanks for the information!

Collapse
 
db325 profile image
db325

When working with the fetch API, how would I put in my access tokens and keys with the request? I've been stuck for two days in this Twitter app.

Collapse
 
kiquenet profile image
Kiquenet

alternatives to Promise?

let vs var ?

Collapse
 
deni404 profile image
Deni Toshevski

How would you loop through the received data, if you want let's say just a certain part of it to display?

Collapse
 
technosmarter profile image
Techno Smarter

We can direct fetch data from the database usng Ajax and PHP
bit.ly/2CKqH6t

Collapse
 
aditya727 profile image
ADITYA727

Sir , I have url and api_key than how can fetch data ...........