Hello! I want to say that I just started working with nodejs. I used before php/laravel. I have 2 tables, one is for posts
one is for posts_actions
. Every user can create a post and other users can like/comment on that post. Every action on that post (eg: like) will be stored in table posts_actions. I'm trying to load the posts from database, loop through them to add an extra object with all the data from table posts_actions. But at the end, when I send back the data to frontend, the data
is empty, why is that and how can I solve this?
app.post("/api/loadposts", function(req, res) {
let posts = [];
let posts_actions = [];
const userid = req.body.userID;
db.query("SELECT \* FROM posts ORDER BY id DESC",
(error, result) => {
if(error) {
return res.status(200).send({ error: true });
}
posts = result;
});
for(let p; p < posts.length; p++)
{
db.query("SELECT \* FROM posts\_actions WHERE post\_id = ? AND user\_id = ? LIMIT 1", \[posts\[p\].id, userid\],
(e, r) => {
if(e) {
posts\[p\].action = \[\];
}
else if(r.length > 0) {
posts\[p\].action = r\[0\];
}
else {
posts\[p\].action = \[\];
}
});
}
res.status(200).send({ data: posts });
});
I know that I must use async/await/promise
, I followed some topics and tried the code below, but the data
I send to frontend is empty. A little help here, what can I do to have the result I want?
async function doQuery(query, params = []) {
function queryData(query, params) {
return new Promise(function(resolve, reject) {
db.query(query, params, function (err, rows, fields) {
if (err) {
return reject(err);
}
resolve(rows);
});
});
}
queryData(query, params).then(function(v) {
return v;
}).catch(function(v) {
return \[\];
})
return null;
}
async function getAllPosts(userid)
{
try {
let posts = await doQuery("SELECT * FROM posts ORDER BY id DESC");
for(let p = 0; p < posts.length; p++)
{
let actions = await doQuery("SELECT \* FROM posts\_actions WHERE post\_id = ? AND user\_id = ? LIMIT 1", \[posts\[p\].id