I am trying to make a nested query, in which I am using the result of the first query in second query the function like is returning an undefined value.I know there is problem with asynchronous nature of nodejs but i can't figure out the solution to convert my code into synchronous.
My code:
function like(article_id,user_id){
var status;
pool.query('SELECT * FROM likes WHERE article_id=$1 AND user_id=$2',[article_id,user_id], function (err, result) {
if (err) {
res.status(500).send(err.toString());
} else {
if (result.rows.length === 0) {
status=`like`;
} else {
status=`unlike`;
}
}
})`
return status;
}
app.get('/article', function (req, res) {
pool.query("SELECT * FROM article",function (err, result) {
if (err) {
res.status(500).send(err.toString());
} else {
if (result.rows.length === 0) {
res.status(404).send('Article not found');
} else {
var middle='';
numRows=result.rows.length;
for(var i=numRows-1;i>=0;i-=1){
var articleData = result.rows[i];
middle=middle + createTemplate(articleData);
var r=like(result.rows[i].article_id,req.session.auth.userId.toString());
middle+=r;
middle+= `</button>`;
middle+=comment_section(result.rows[i].article_id.toString())+`<hr><hr>`;
}
res.send(middle);
}
}
});
});
Note:
createTemplate(articleData)
and comment_section(result.rows[i].article_id.toString())
are synchronous.