简体   繁体   中英

How do I return the results of .query in a class

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");

In the "asynchronous" programming model (AP), one provides a callback in which the result of the query is used. Something like:

myDatabase = new dataBase("fee","fi","foo","fum");
myDatabase.query("SELECT * FROM users",function(err,result){
    // check for error and do something with result
});

The whole idea behind AP is that, rather than waiting, things can and do occur outside of your normal program flow--for example, as data become available--and so, you must use whatever result they produce when it becomes available.

This is why AP callbacks do not return values. There is no context into which they can return.

Think about it like sending a certified letter through the Post Office. You hand off your letter to the postal person and rather than wait until the letter is delivered and the receipt is available, you go do other things, leaving the instruction that once the receipt is in-hand, it should be delivered to your house or you should be called to pick it up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM