I'm having a really difficult time grasping asynchronous callbacks and variable storage in socket.io. I want the code in the callback function to be executed after all the queries are made. However, I don't know where to place the callback() method call so it executes after everything is finished. I would greatly appreciate any and all help.
//The code below queries a database and stores the information in a json object.
var mysql = require('mysql')
var io = require('socket.io').listen(3000)
var db = mysql.createConnection({
host: '',
user: '',
password: '',
database: '',
port: 3306,
})
db.connect(function(err){
if (err) console.log(err)
})
console.log(1);
io.sockets.on('connection', function(socket){
socket.on('key', function(value){//client side has a onclick() function that emits 'key'
console.log(2);
var total = {};
var personalTable = []
var liwcTable = []
var id = value;
help(total, function(total) {
console.log(4);
console.log("total = " + JSON.stringify(total));
socket.emit('total', total);/emits to client
});
function help(total, callback) {
console.log(3);
db.query('SELECT * FROM `a` WHERE `userId` =' + id)
.on('result', function(data){
liwcTable.push(data)
})
.on('end', function(){
total["initial liwcTable"] = liwcTable;
})
db.query('SELECT * FROM `b` WHERE `userId` =' + id)
.on('result', function(data){
personalTable.push(data)
})
.on('end', function(){
total['personalTable'] = personalTable;
})
callback(total)//needs to be executed after the queries are done.
}
})
})
The code goes into the callback method before the queries have a chance to finish. I also don't understand how I can be updating my json object "total" when the scope of the query callbacks are limited.
You have many solutions to trigger a callback after all wanted actions. You can for example, create a singleton called after each query, which will trigger the final callback.
function help(total, callback) {
var nbEndedQueries = 0,
amountOfQueries = 2;//nb of linked queries
function singleton() {
//increments the nbEndedQueries variable and tests if the max is reached
if(++nbEndedQueries >= amountOfQueries)
callback();
}
db.query(... //query calling)
.on('result', ...//some behaviours
singleton();
)
db.query(... //query calling)
.on('result', ...//some behaviours
singleton();
)
//...
}
An other solution is to use the promises. Many modules like Q or the ECMA6 polyfill provide you this feature which is totaly awesome
sample with ecm6 promise polyfill
//promisification of the query method
function query(string) {
return new Promise(function(resolve, reject) {
db.query(string)
.on('result', resolve)
//i supposed an error event exist
.on('error', reject);
})
}
//and now the usage
function help() {
//basic method
//first query calling
query('your query string')
.then(function(result) {
//behaviour
//second query calling, the result will send to the next 'then' statement
return query('second query');
})
.then(function() {
//behaviour
//at this point, all queries are finished
callback() ;
});
}
//parallelized sample
function help() {
//starts all queries and trigger the then if all succeeds
Promise.all([query('your query string'), query('second query')])
.then(function(results/*array of results*/) {
//behaviour
callback();
})
}