Reputation: 89
I am receiving the names of a few animals in query separated by commas. Now I have to call an API that only accepts one animal name at a time. I want to call the same API once for each animal and push the jsonified data in an array before I respond to my client.
I am getting an empty array on my client while testing and to my understanding, that is happening because the res.send() is executed while the promise is waiting to be resolved.
Any solution is greatly appreciated.
router.get('/animals', async (req, res) => {
const mammalsArray = req.query.mammals.split(',');
let final = [];
await mammalsArray.forEach(async function(mammal) {
const response = await fetch(`https://someapi.com/pedia?tag=${mammal}`);
const json = await response.json();
final.push(json);
});
res.send(final);
});
Upvotes: 1
Views: 1285
Reputation: 4037
async
function returns a promise. You want to save all the promises and when all the promises are resolved, you want to continue.
You can wait for all the promises with Promise.all
.
I used map
instead of forEach
to map all array values to promises.
router.get('/animals', async(req, res) => {
const mammalsArray = req.query.mammals.split(',');
let final = [];
let promisesArray = mammalsArray.map(async function(mammal) {
const response = await fetch(`https://someapi.com/pedia?tag=${mammal}`);
const json = await response.json();
final.push(json);
});
await Promise.all(promisesArray);
res.send(final);
});
Upvotes: 2