const returnPostData = async (req, res, initialPostsQueryArray) => {
const promises = initialPostsQueryArray.map((post) => {
let postObject;
voteCount = sumValues(post.voting_options);
pool.query('SELECT voting_option FROM votes WHERE user_id = $1 AND post_id = $2',
[req.user.userId, post.post_id],
(error, results) => {
if (error) {
console.log(error);
return res.json({'Error': error.detail});
}
userVoteOption = results.rows[0].voting_option;
});
postObject.voteCount = voteCount;
postObject.userVoteOption = userVoteOption;
return postObject;
});
return Promise.all(promises).then(postData => {
return res.json(postData);
})
}
I'm trying to return an array of the postObjects for each post. For some reason it keeps on printing null for these objects because the return res.json is somehow running before the promises are even done. Any help is appreciated.
I had this problem before and used the same code, but it didn't work for this one for some reason.