In my node.js app, I have the following code to get the last mark of a given user.
app.get('/user/:token/mark/last', function(req, res){
var user_token = req.params.id;
// Mark to be returned
var last_mark = 0;
// Get user
var get_user = client.query("SELECT id FROM user where user_token = $1", [user_token]);
// Get mark: handle sensor retrieved
get_user.on('row', function(row) {
get_mark = client.query("SELECT * FROM mark WHERE user_id = $1 order by date desc limit 1", [row.id]);
get_mark.on('row', function(mark) {
last_mark = mark.value;
console.log("LAST MARK:" + last_mark); // OK IT DISPLAYS "LAST MARK:16"
});
// Error checking
get_mark.on("error", function (err) {
console.log("ERROR");
});
});
// Check database errors
get_user.on("error", function (err) {
console.log("NO SUCH USER");
});
// Finalize
get_user.on("end", function () {
console.log("LAST MARK:" + last_mark); // KO IT DISPLAYS "LAST MARK: 0"
});
})
The problem is I do not get the correct "last_mark" (I get 0), as if the assignement was not done.
Do you have any idea ?
client.query
to shut down the outerclient.query
as most DB interfaces only allow one active statement per connection..query
calls so the nesting should be okay. But, I don't know what order things will occur in (or even any particular order is guaranteed): will the 'end' event be triggered before or after the the inner query does anything? Have you considered rewriting the query with a JOIN to avoid the event order problem completely?