Reputation: 1128
This is the snippet of code. Some small things have been changed.
app.get('/user/:username', async (req, res) => {
axios.get(`${baseApiUrl}/users/${req.params.username}`, options)
.then(userData => {
let user = userData.data
user.events.forEach(event => {
if (event.type === 'Purchase') {
event.cart.forEach(async item => {
axios.get(item.url, options)
.then(itemData => {
item.itemData = itemData.data }
})
.catch(err => {
console.log('ERROR', err)
})
})
}
})
res.json({ events })
})
})
I first hit the endpoint to grab the user data. Then I loop through the events array and if it is of type purchase
, it loops through the cart array. The cart array contains items with a parameter called url
which is another endpoint I need to hit. That then returns additional information and I add it onto the item
object.
But when I look at events
, it doesnt contain the new key/value I added. I am pretty sure this has something to do with async/promises. Would love some advice!
Upvotes: 1
Views: 662
Reputation: 842
this is by no any means perfect, but the code should look something like this:
// Function to fetch info of item.
const fetchItemInfo = async (url) => {
console.log(`Fetching ${url}`);
const info = await axios(url); // API call to get item info.
return {
data: info.data
};
}
// function to loop through the cart item and make them promise to be resolved
const getCartItemData = async (cart) => {
// you can use for loop and use push to requests array, but I use map in this case
const requests = cart.map(cartItem => {
return fetchItemInfo(cartItem.url).then(info => {return info;});
}
return Promise.all(requests);
}
// then in your code, you can call the getCartItemData function like this:
if (event.type === 'Purchase') {
getCartItemData(event.cart).then(itemData => console.log(itemData));
}
Upvotes: 1