Reputation: 1
I'm searching for an image and name by Rick&Morty's api, I've already been successful with a photo and name, but I want the method to return one more image, totaling two images of the characters and their names.
gerarValorAleatorio = () => {
return Math.floor(Math.random() * 671);
}
pegarPersonagem = () => {
let numeroAleatorio = gerarValorAleatorio();
return fetch(`https://rickandmortyapi.com/api/character/${numeroAleatorio}`, {
method:'GET',
headers: {
Accept: 'application/json',
"Content-type": 'application/json'
}
}).then((response) => response.json())
.then((data) => {
imagem.src = data.image;
imagem.alt = data.name;
nomeDoPersonagem = data.name;
nome.innerHTML = `${nomeDoPersonagem}`;
imagem2.src = data.image;
imagem2.alt = data.name;
nomeDoPersonagem = data.name;
nome2.innerHTML = `${nomeDoPersonagem}`;
Upvotes: 0
Views: 62
Reputation: 63579
The fetch API is based on promises. So it means you can group fetch calls in an array and use Promise.all to wait for their completion.
When the data is returned (as an array) you can iterate over it.
function fetchAPI(n) {
return new Promise((res, rej) => {
setTimeout(() => {
res(`Done ${n}`);
}, 2000)
});
}
const arr = [fetchAPI(1), fetchAPI(2)];
Promise.all(arr).then(data => {
data.forEach(str => console.log(str));
});
Upvotes: 1