I'm building a recursive query:
app.get('/showposts', function(res, req) {
getPosts(id){
connection.query("SELECT * FROM posts WHERE someId = 2", (err, rows) => {
allIds = [];
for(var i = 0; i < rows.length; i++){
allIds.push(rows[i].id_post);
getPosts(rows[i].id_post) // <= calling the function again.
}
console.log("The IDs : " + allIds )
// res.send fails stating response was already sent
});
};
getPosts(1) // <= initial call to the function.
});
This works well except that the response is sent for each and every time. So if there are 5 results (3, 7, 8, 11, 12
) when calling the function first time and calling it again from the for loop
there is 1 result (13
, cause for this id_post
, someId=3
) I get :
I want to send only 1 response with the entire array. But if I do res.send, I get error:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
What am I doing wrong? Please help.