Currently, I am developing a server route to execute API calls.
I have encountered the need to make two separate fetch requests as I require additional information that is not available in the first fetch.
The issue lies in declaring a variable outside of the promise scope, causing my res.send
function to not wait until the array is populated entirely.
My objective is to iterate until result 9 is achieved (predefined filters from TheDogApi cannot be used to display nine results).
if (req.query.name) {
var myRes = [];
fetch(`https://api.thedogapi.com/v1/breeds/search?name=${req.query.name}&apikey=${key}`)
.then(r => r.json())
.then( data => {
for (let i = 0; i < 8 && i < data.length; i++) {
fetch(`https://api.thedogapi.com/v1/images/${data[i].reference_image_id
}`)
.then(r => r.json())
.then(datos => {
myRes.push({ ...data[i], ...datos });
})
}
})
.then(res.send(myRes))
}
Your assistance on this matter would be greatly appreciated!