xxxxxxxxxx
52
// Daniel Shiffman
// http://codingtra.in
// Promise.all()
// Video: https://youtu.be/01RTj1MWec0
// To run this sketch, replace ADD_YOUR_KEY
// in the urls below, with your own API key.
// Giphy API: https://developers.giphy.com/
// Giphy API Tutorial: https://youtu.be/mj8_w11MvH8
// Wordnik API: https://developer.wordnik.com/
// Wordnik API Tutorial: https://youtu.be/YsgdUaOrFnQ
// Note: In this file, "let" was changed to "const" where it was appropriate to be consistent with ES6.
const wordnikAPI =
"https://api.wordnik.com/v4/words.json/randomWord?&api_key=ADD_YOUR_KEY";
const giphyAPI =
"https://api.giphy.com/v1/gifs/search?rating=G&api_key=ADD_YOUR_KEY&q=";
function setup() {
noCanvas();
let promises = [];
for (let i = 2; i < 10; i++) {
promises.push(wordGIF(i));
}
Promise.all(promises)
.then((results) => {
for (let i = 0; i < results.length; i++) {
createP(results[i].word);
createImg(results[i].img);
}
})
.catch((err) => console.log(err));
}
async function wordGIF(num) {
const response1 = await fetch(
`${wordnikAPI}&minLength=${num}&maxLength=${num}`
);
const json1 = await response1.json();
const response2 = await fetch(giphyAPI + json1.word);
const json2 = await response2.json();
const img_url = json2.data[0].images["fixed_height_small"].url;
return {
word: json1.word,
img: img_url,
};
}