0

My function returns "undefined", when I am waiting "result". What is a problem?

getUserDictionary = (user_id) => {
  connection.connection.query("SELECT eng_word, ru_word FROM `dictionary` where user_id="+user_id,
   function (error, results, fields) {
    if (error) throw error;
      console.log(results);
      return results;
    });
}

console.log(getUserDictionary(1));

"results" shows what I want (no problem with Data base connection). But last console.log with function returns undefined

Nikita Polevoy
  • 319
  • 5
  • 17

1 Answers1

1

You are leaving yourself wide open to a SQL injection attack

Do not do this: "SELECT eng_word, ru_word FROM dictionary where user_id="+user_id

If this is just a pet project, fine, but if you're opening it up to the internet anyone could erase your database. Use prepared statements instead. If you are using mysqljs you can drop this in as a replacement for your current query:

connection.query('SELECT eng_word, ru_word FROM dictionary WHERE user_id = ?', [user_id], function (error, results, fields) {

Anyways...

Your problem is that connection.connection.query() is an asynchronous function. If you would like it to behave synchronously, you can use the async/await pattern supported in ES6. Otherwise, you can structure your code to act in response to the return from query().

Here is what it would look like using async/await:

getUserDictionary = (user_id) => {
  return new Promise((resolve, reject) => {
    connection.connection.query("blah blah blah",
      function (error, results, fields) {
        if (error) {
          reject(error);
          return;
        }
        console.log(results);
        resolve(results);
      });
  });
};

Which you can use like

async () => {
  let results = await getUserDictionary(0);
  console.log(results);
}