If I didn't need to worry about asynchronous code, this is what it'll look like:
app.get('/user/:username/events', async (req, res) => {
// Grab all events by that user
let events = await axios.get(`${baseApiUrl}/users/${req.params.username}/events`, options).then(d => d.data)
// Loop through events
events.forEach(event => {
// If event type is A_Event
if (event.type === 'A_Event') {
// Loop through objArr array
event.payload.objArr.forEach(async obj => {
// Grab additional data through endpoint
// that lives in obj
let data = await axios.get(obj.url)
// Append data back onto obj
obj.objData = data
})
}
})
// return events obj with objData appended to each obj within
// objArr
res.json({ events })
})
But this doesnt work because it returns events
before its done grabbing all the data.
I tried doing something with Promise.all
but couldnt get what I needed to get.
events.map(async event => {
if (event.type === 'A_Event') {
getData(event.payload.objArr)
.then(objData => {
// This returns an array of objData that
// then needs to be added back to the specific obj
// it came from
event.payload.objArr.forEach((obj, i) => {
obj.objData = objData[i]
})
})
}
res.json({ events })
})
const getData = async objArr => {
const requests = objArr.map(async obj => {
const data = await axios.get(obj.url, options)
return {
stats: data.data.stats,
created_at: data.data.created_at
}
})
return Promise.all(requests)
}
Would really appreciate the help with this. Been stuck on this problem for a good bit.
EDIT
Tried switching to a for of
loop according to this post: Using async/await with a forEach loop... No luck but I think its a step in the right direction.
events.forEach(async event => {
if (event.type === 'A_Event') {
for (let obj of event.payload.objArr) {
let objData = await axios.get(obj.url, options)
obj.objData = objData
console.log('setting value')
}
}
})
res.json({ events })
console.log('returned value')
I get returned value
before I get setting value
...