I need to make two calls to two rest api, in the first with one of the data obtained, pass it to the second url and ai obtain what I want, I could achieve it with the code below but my boss tells me that it is wrong, first it I did with asyn await and it told me not to use it, then later with fetch and axios but it is not well written, what would be the correct way to do it with both axios and fetch cases? with axios
axios.all([axios.get(`${urlRestApi}`)]).then(
axios.spread(response1 => {
let arrPost = response1.data.map(res => {
return {
titulo: res.title.rendered,
contenido: res.content.rendered,
extracto: res.excerpt.rendered,
idImagen: res.featured_media,
};
});
console.log("AQUI", arrPost);
arrImg = arrPost.map(image => {
axios.get(`${urlImage}/${image.idImagen}`)
.then(urls => { // urls returns 10 objects each with a corresponding image
arrUrl.push(urls.data); //for this reason I put all 10 in an array, but it happens 10 times
if (arrUrl.length === 10) { // that's why when .length is 10 I go through it and assign what I want
let arrImage = arrUrl.map(img => {
return {
imagenes: img.source_url,
};
});
console.log("TEST", arrImage);
mostrarHTML(arrImage, arrPost); //I already have everything I run my function to print the data obtained
}
});
});
})
);
and with fetch
fetch(`${urlRestApi}`)
.then(respuesta => {
return respuesta.json();
})
.then(data => {
let arrPost = data.map(data => {
return {
titulo: data.title.rendered,
contenido: data.content.rendered,
extracto: data.excerpt.rendered,
idImagen: data.featured_media,
};
});
console.log(arrPost);
arrImg = arrPost.map(image => {
fetch(`${urlImage}/${image.idImagen}`)
.then(res => {
return res.json();
})
.then(urls => { // // urls returns 10 objects each with a corresponding image
arrUrl.push(urls); //for this reason I put all 10 in an array, but it happens 10 times
if (arrUrl.length === 10) { // that's why when .length is 10 I go through it and assign what I want
arrImage = arrUrl.map(image => {
return {
imagenes: image.source_url,
};
});
console.log("aqui", arrImage);
mostrarHTML(arrImage, arrPost); //I already have everything I run my function to print the data obtained
}
});
});
})
.catch(error => {
console.log(error);
});