I am new in node.js . I am facing a problem with a GET request . I am using 2 mysql query. First one is returning some ids , I am using those Ids in my 2nd query . In the console all the rows are successfully printing but in the browser only the first row.
My Code structure is like :
function userProjects(request, response) {
connection.query("1st query", function(err, first_output, fields) {
response.writeHead(200, {
"Content-Type": "application/json"
});
for (var i in first_output) {
var obj = first_output[i];
connection.query("select * from table where parent_id=" + obj.id, function(err, apartmentRows, fields) {
console.log(apartmentRows);
response.write("apartments are : " + JSON.stringify(apartmentRows));
response.end();
});
}
});
}
So far I have understood by surfing various contents ,due to response.end() it is stopping to get remaining rows here . That's why all are not printing . But I failed to figure out the solution to solve it .
Thanks in advance.
You will need to ensure that all of your queries get executed before calling response.end(). My naive approach would be to set a counter flag to check the number of queries performed. Once all the queries have been performed just end the response.
function userProjects(request, response) {
connection.query("1st query", function(err, first_output, fields) {
response.writeHead(200, {
"Content-Type": "application/json"
});
var totalQueries = 0;
for (var i in first_output) {
var obj = first_output[i];
totalQueries++; //increases the number of query performed
connection.query("select * from table where parent_id=" + obj.id, function(err, apartmentRows, fields) {
console.log(apartmentRows);
response.write("apartments are : " + JSON.stringify(apartmentRows));
totalQueries--; //decreases the query count
if (totalQueries == 0) //when all queries are performed end the response
response.end();
});
}
});
}