I'm writing an application in NodeJS using coffee script and I need to store the results of a sql query made by a class into a variable that that class can return.
I have something like
class dataBase
mySQL = require('mysql');
connection = null;
queryResults = null;
constructor:(host,user,password,database)->
connection = mySQL.createConnection({
host : "#{host}",
user : "#{user}",
password : "#{password}",
database : "#{database}",
});
connection.connect;
then later in the class I have a function called query that queries the database and returns the results.
query:(input) ->
connection.query("#{input}",(err,result)->
queryResults = result;
);
return queryResults;
The problem is because the function in connection.query always runs asynchronously so return queryResults always returns null.
Is there anyway I can fix this so that query() will return the value of the result if I do something outside of the class like:
myDatabase = new dataBase("fee","fi","foo","fum");
users = myDatabase.query("SELECT * FROM users");