I am working on a project and on the newer side of Node. This is someone else's original implementation and I'm having an issue with promises and I know it most likely has to do with async/await or promise.all but I've spent alot time trying and still not getting the desired result.
I am going to the PlaceStore and returning a promise to get a list of people from a sql database. After I have the list of people. I map over the the list so I can have each person's id. Inside the map (which may be the problem because maps are not asynchronous) I am trying to find the most recent thing done by that person by calling the getMostRecentThingByPerson function that goes to the ThingStore to get the most recent thing.
When I log the resent in the result of the getMostRecentThingByPerson it does log the correct values but I don't know how to make the value available in the map function so I can update and return the object containing the 'Most Recent Thing' and export it to Csv.
I've read alot about how this is an important topic and thank you so much for your guidance with this issue.
exports.exportPeople = (req, res, next) => {
const id = req.body.id;
const place = req.place;
PlaceStore.findPerson(place, async (err, people) => {
if (err) {
return new Error(err);
}
const peopleForCsv = people.map((person) => {
const mostRecentThing = this.getMostRecentThingByPerson(person.id) // tried adding await here but does not work because of the map.
return {
'First Name': person.first_name,
'Last Name': person.last_name,
'Most Recent Thing': mostRecentThing
};
});
const json2csvParser = new Parser({ delimiter: ',' });
const csv = json2csvParser.parse(peopleForCsv);
return res
.status(200)
.attachment('people_' + id + '.csv')
.set('Content-Type', 'text/csv')
.send(csv);
});
};
exports.getMostRecentThingByPerson= (id) => {
ThingStore.getThings({"person_id": id}, (err, things) => {
if (err) {
return new Error(err);
}
result = things.rows.length > 0 ? things.rows[0].capture_date : ''
console.log(`Recent thing result for ${id}`, result) //example date
return result
})
return result
}