- Tutorial by: Hassan Algoz
- YouTube Channel: https://www.youtube.com/channel/UCaD5hX1OzVezzbIqHm3VHsQ
- Vocabulary: API,
fetch,XMLHttpRequest, promises, GET, HTTP, asynchronous.json(JSON): JavaScript Object Notation
fetch is the modern equivalent to XMLHttpRequest. fetch uses promises.
A function that uses promises can chain .thens to allow for asynchronous flow that listens for when the task is completed, rather than wait.
fetch('http://api.icndb.com/jokes/random/3')
.then(function(response) {
return response.json()
})
.then(function(json) {
// json is just a JavaScript Object
console.log(json)
})Also, try to visit the url in the browser to see how the structure of the returned json looks like.
We notice that the returned json contains the value attribute/property, which contains an array of values.
So, we modify our second .then block of code to:
.then(function(json) {
let arrayOfValues = json.value
for(let i = 0; i < arrayOfValues.length; i++) {
let element = document.createElement('h3')
element.innerHTML = arrayOfValues[i].joke
document.body.appendChild(element)
}
})The above code takes the parsed json and adds h3s to the HTML.
Remember, using forEach you can do the same thing:
json.value.forEach(function(val) {
let element = document.createElement('h3')
element.innerHTML = val.joke
document.body.appendChild(element)
})To demonstrate what promises means, and what asynchronous means.
Note that although the above fetch function executes before any code below it,
the code below will finish execution first because it doesn't take as much time.
And this happens because JavaScript is not "waiting" the fetch to finish before strating the next instruction.
And that is accomplished by what we call Asynchronous Code.
TL;DR this block of code will finish before fetch whether you put it before or after fetch.
let element = document.createElement('div')
element.innerHTML = "<h1>HELLO</h1>"
document.body.appendChild(element)You will see the h1 element appear above the jokes h3s in the HTML page.
To practice the fetch API, you can try this API endpoint (url): https://randomuser.me/api/?results=2 which you can fetch json from.
- search the internet for anything you don't understand
- Share with love and please don't attribute this work to yourself.
يسلمو كتير استاذ حسن على الشرح الرائع