I have the following code:
var data = 0;
connectionSelectPackageId.connect();
let sqlSelectPackageId = "SELECT MAX(packageId) as maxId FROM recipients";
connectionSelectPackageId.query(sqlSelectPackageId, function(err, rows){
if(err) {
throw err;
} else {
for(var i=0; i< rows.length; i++) {
data = data + rows[i].maxId;
console.log(data);
};
};
});
connectionSelectPackageId.end();
console.log(data);
The issue is that console.log(data) get executed before the query has completed, and hence its value is the default which is zero instead of taking into account the added value in the query.
I would like to use the data variable in subsequent code. Hence, my question is how can i run the remaining portion of my code only after this query has been completed? The variable needs to work outside of the scope of the query.
The follow up query
connectionInsert.connect();
// Insert into the recipients the hashtag and information needed to opon the lock
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
var dateTime = getDateTime();
// Add email later on
let sqlInsert = 'INSERT INTO recipients (date, ..., ..., ..., ..., ..., ..., data) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
connectionInsert.query(sqlInsert, [dateTime, ..., ..., ...,...,..., ..., data], function(err, rows, fields) {
});
connectionInsert.end();