I'm practicing my javascript skills doing a joke machine that collects jokes from an API and displays them, my problem is that currently, I'm using .then()
which is fine, but I want to know how do I get my results in an array that doesn't have to wait for .then()
like in fetchJokes().then(jokes => console.log(jokes));
I used to have a function that navigated the array like this:
let counter = 0;
let jokes = [joke1, joke2, joke3, joke4];
function nextJoke(jokes) {
counter++;
counter %= jokes.length; // start from 0 if we get to the end of the array
return jokes[counter]; // give us back the actual item
}
That's how it was used before fetching from the API.
And this is my current code:
const url = "https://api.icndb.com/jokes/random/5";
const fetchButton = document.querySelector("button[type=button][value=Fetch]");
async function fetchJokes() {
let jokes = [];
let data = await (await fetch(url)).json();
for (let i = 0; i < 5; i++) {
jokes[i] = data.value[i].joke;
}
return jokes;
}
fetchButton.addEventListener("click", () => {
fetchJokes().then(jokes => console.log(jokes));
});
<button type="button" value="Fetch">Fetch Jokes</button>
So I have figured out how to use buttons and all that jazz, just asking for help on how to pass the object that im receiving from fetchJokes()
and store it in an Array.