Created
July 9, 2020 06:48
-
-
Save KennFatt/79e89cd702eff3cee4aff0a4c20021e2 to your computer and use it in GitHub Desktop.
Asynchronous Programming with javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Asynchronous programming concept. | |
* | |
* Please comment one of the methods available! | |
*/ | |
const GIPHY_API = "http://api.giphy.com/v1/gifs/search?api_key={YOUR_GIPHY_API_KEY}&q="; | |
const WORDS_API = "https://random-word-api.herokuapp.com/word?number=1&swear=0"; | |
/** | |
* DOM Initialize | |
*/ | |
const paragraph = document.createElement("p"); | |
paragraph.textContent = "Please wait..."; | |
document.body.appendChild(paragraph); | |
const image = document.createElement("img"); | |
document.body.appendChild(image); | |
/** | |
* Promises with chaining method. | |
*/ | |
(_ => { | |
fetch(WORDS_API) | |
.then(wordData => wordData.json()) | |
.then(wordsJson => { | |
paragraph.textContent = wordsJson[0]; | |
return fetch(GIPHY_API + wordsJson[0]); | |
}) | |
.then(giphyData => giphyData.json()) | |
.then(giphyData => { | |
if (giphyData.data.length <= 0) { | |
throw new Error("No image found for: " + paragraph.textContent); | |
} | |
image.src = giphyData.data[0].images.original.url; | |
}) | |
.catch(err => console.error(err)); | |
})(); | |
/** | |
* Syntatic sugar for promises that introduced in ES8 (async/await). | |
*/ | |
(async _ => { | |
const wordsResponse = await (await fetch(WORDS_API)).json(); | |
const giphyResponse = await (await fetch(GIPHY_API + wordsResponse[0])).json(); | |
if (giphyResponse.data.length <= 0) { | |
/** Before we throw an exception, let's update the DOM first */ | |
paragraph.textContent = wordsResponse[0]; | |
throw new Error("No image found for: " + wordsResponse[0]); | |
} | |
/** Rendering image first will gives different experience tho */ | |
image.src = giphyResponse.data[0].images.original.url; | |
paragraph.textContent = wordsResponse[0]; | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Asynchronous Programming</title> | |
</head> | |
<body> | |
<script src="js/app.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment