I’ve just ventured into the wonderful world of server-side javascript and am still getting the hang of asynchronous processing. After messing around with a node project I came to the realization that this javascript is like a lot of my past girlfriends — they just won’t callback. Anyways I was hoping someone could help me out…here’s the code with an explanation below:
//this is the function I'm calling to
function queryDb(connection, sql){
connect(connection, function(){
connection.query(sql, function(err, results){
if(!err){
return results;
end(connection);
}
else{
throw err;
}
});
});
}
And Here is where I make the call. After the call I want some code to execute, but not until this function is done processing (it’s actually a query to the database, so takes a little longer time and my js just keeps on going).
var queryResults = db.queryDb(db.connection, "SELECT * FROM Clients");
if(queryResults){
console.log(queryResults);
req.dbResults = queryResults;
next();
}
else{
console.log('The query results where not returned here is the queryResults variable: ' + queryResults);
}
What I’d like to have happen is the results to be returned from the parent function and then a callback run by the child function doing something with the results. I tried this:
queryDb(db.connection, "SELECT * FROM Clients", function(){
if(results){
console.log(results);
req.dbResults = results;
next();
}
else{
console.log('The query results where not returned here is the queryResults variable: ' + results);
}
});
But I can’t access the results returned by the parent function in the callback of the “calling function”.
You are not doing anything with the third argument so your callback is not going to be called.
And with your last example, the call is asynchronous so what you are trying to do is not going to work.
And to fix the code to work with that mystery 3 param.