0

I try to access the results[0].guess, to return them to the caller. The console.log(getGuess(12,4)(the parameters are not important) just returns undefined. How do I have to access the result?

Note: I am using Node.js with mysql.

var getGuess = function(userId, gameId) {
var query = 'SELECT * FROM guesses WHERE user_id = ' + connection.escape(userId) + ' AND game_id = ' + connection.escape(gameId);
connection.query(query, function(err, results) {
if (err) {
  console.log(err);
  return;
}
var guess = results[0].guess;
return;
});
return guess;
};
Marc
  • 11
  • 4
  • Do you understand why `.query` takes a callback instead of returning the result set directly to you? It's done because the queries are performed asynchronously, and the callback is invoked at some time in the future, long after the `return guess;` line. Read through [this question](http://stackoverflow.com/q/23667086/1233508) to get the basic idea of what's going on. – DCoder Sep 27 '15 at 09:59
  • Okay, so the .query is asynchronous. How do I get the result value to be returned by the getGuess-Function? Is there something like a "return return [something]"? – Marc Sep 27 '15 at 10:08
  • Or is there a way to change the standard-return of the .query-function to match my style? Like: `var guess = connection.query(query, function(err,results) { ... return myValue }` – Marc Sep 27 '15 at 10:10
  • There are various ways to deal with asynchronous code, such as Node streams, Promises, callbacks... Streams and Promises are quite close to regular synchronous code, but you still need to "get" them and adapt your mindset and your code. – DCoder Sep 27 '15 at 10:26

0 Answers0