it is first time to use node js So this question can be very basic question. I tried to use callback instead of just returning value but I couldn't solve the problem.
I heard that mysql query is executed after other code in node js. But I want to put (if condition) query in the middle of the code and check the condition before implementing codes below query.
I am doing IoT thing ( sensor + android app + aws ubuntu server with nodejs and using mysql for database ) I want to check if the sensor is working fine before adding data to server database. So, I put the code to check if sensors are working fine before storing data in database. ( check by comparing the results from two sensors. )
But the problem is that mysql query(to check if the sensors are right) is executed later than other code in node.js so I cannot check the condition in the middle. How can I run condition query in the middle of the code and return any condition value?
app.get('/log', function(req, res){
r = req.query;
result_error = error_check(r.nickname);
console.log("error check result"+result_error);
insert_temp(r.nickname,r.left_num,r.right_num);
//this function is called after error_check function, but when I saw the result, console.log in this function is called earlier than error_check function
res.end('OK:' + JSON.stringify(req.query));
});
function error_check(nickname){
var sql = mysql.format('select sum(left_num) as left_sum, sum(right_num) as right_sum from temp where nickname = ? and today_date = date(current_date());',nickname);
var query = connection.query(sql,function(err,result){
if (err) throw err;
console.log("Error check/// left_sum is "+result[0].left_sum + " right_sum is "+result[0].right_sum);
if ((result[0].left_sum - result[0].right_sum >=30 )|| (result[0].right_sum - result[0].left_sum >=30 )){
console.log("Sensor is broken");
return 1;
}
else{
return -1;
}
});
console.log(query);
}
/////////////////////////////but the result is
error check result undefined
(this is from insert_temp function! )nickname is ? left_num is ? right_num is ? gucheol 0 1
(this is from error_check function! this function is called before inset_temp function. error_check function is executed late...so I cannot check if sensor is wrong )
Error check/// left_sum is 0 right_sum is 45
Sensor is broken
///but if we see the result from console/////
error check result undefined
(this is from insert_temp function! )nickname is ? left_num is ? right_num is ? gucheol 0 1
Error check/// left_sum is 0 right_sum is 45 Sensor is broken
(this is from error_check function! this function is called before insert_temp function. error_check function is executed late...so I cannot check if sensor is wrong )