Start Here: Zero to JavaScript — Callback/Fetching data/Working with JSON
By: Jack Yeh
Tags: Easy, Internet, Beginners Guide, JavaScript

Load Any Website/Api Endpoint with fetch()

Turns out, loading web address is such a common task, JavaScript comes with a built-in function for it. Try running the following to see what it does:

fetch('https://api.thedogapi.com/v1/images/search')

< Promise {<pending>} < Promise { } await fetch('https://api.thedogapi.com/v1/images/search')

< Response {type: "cors", url: " < Response {type: "cors", url: " https://api.thedogapi.com/v1/images/search ", redirected: false, status: 200, ok: true, …} (await fetch('https://api.thedogapi.com/v1/images/search')).text()

< Promise {<pending>} < Promise { } await (await fetch('https://api.thedogapi.com/v1/images/search')).text()

< "[{"breeds":[{"weight":{"imperial":"23 - 28","metric":"10 - 13"},"height":{"imperial":"15.5 - 20","metric":"39 - 51"},"id":111,"name":"Finnish Spitz","bred_for":"Hunting birds, small mammals","breed_group":"Non-Sporting","life_span":"12 - 15 years","temperament":"Playful, Loyal, Independent, Intelligent, Happy, Vocal"}],"id":"hYsMv3NQi","url":" < "[{"breeds":[{"weight":{"imperial":"23 - 28","metric":"10 - 13"},"height":{"imperial":"15.5 - 20","metric":"39 - 51"},"id":111,"name":"Finnish Spitz","bred_for":"Hunting birds, small mammals","breed_group":"Non-Sporting","life_span":"12 - 15 years","temperament":"Playful, Loyal, Independent, Intelligent, Happy, Vocal"}],"id":"hYsMv3NQi","url":" https://cdn2.thedogapi.com/images/hYsMv3NQi.jpg ","width":630,"height":423}]"

When we run fetch with a web address, it returns a Promise object. Promise is a basic Data Type in JavaScript. When you see Promise being returned, you can use the “await” operator in front of it to get to the actual return value.

When we await on fetch(“https://api.thedogapi.com/v1/images/search”), we end up receiving a Response object. On a moment’s glance, it looks like status is 200, and field ‘ok’ is true.

This is a good sign, it means our attempt to get JSON data from that web address successfully, but we don’t see the actual response yet.

Response object has a class member method called text(). When we call text(), we receive yet another Promise. No problem, let’s use another “await” on the whole thing. A string is returned containing the JSON Data we care about, this is good progress.

We can try to convert the JSON in string form into JSON objects (in this case an Array). This is usually done with the built-in JSON.parse() function. But, if you read the documentation on fetch, it turns out there is another convenience method called json(), which can be used like this:

var data = await fetch('https://api.thedogapi.com/v1/images/search').then(result => result.json())

< undefined

> data[0].url

< " < undefined< " https://cdn2.thedogapi.com/images/x-LJYrq37.jpg

First, we call fetch(‘https://api.thedogapi.com/v1/images/search') to get a Promise.

Next, we call .then() on the Promise object. This member function takes in a callback.

Callback takes this form:

inputVariable => (step1;step2;step3; return value) or (inputVariable) => {

step1;

step2;

step3;

...

return value;

}

Oh, that’s right, Callbacks are just functions without names! Also instead of the function keyword, we write =>

Promise and the then() function takes a callback, and when it is ready to give you the result, it will pass that as input into the callback.

Putting it altogether, we have this function:



const result = await fetch('

return result[0].url;

} function getDogImageUrl() {const result = await fetch(' https://api.thedogapi.com/v1/images/search').then(result => result.json())return result[0].url; VM917:2 Uncaught SyntaxError: await is only valid in async function

Huh… we want to use await on the Promise, but Chrome tells us the await operator can only be used inside async functions.

Ok, let’s try this:

async function getDogImageUrl() {

const result = await fetch('https://api.thedogapi.com/v1/images/search').then(result => result.json())

return result[0].url;

}

Good going! Our function is ready for use. Next, we will cover how to make a single dog image show up on the screen.