0

Why doesn't this work? The result Object live only in the query scope?

 const mysql = require("mysql");

 const conn = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "db",
});

var r;

conn.query('select * from table', (err,result,fields) => {
   console.log(result); // It works.
   r=result; 
   console.log(r);// It works.
});

console.log(r); // undefined
Shadow
  • 33,525
  • 10
  • 51
  • 64
Matt
  • 33
  • 6
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Sep 20 '20 at 10:57

2 Answers2

1

What is happening here is a Race condition. The conn.query is passing the data (result) back only once the database query has completed. The rest of the application is continuing to be ran. So, your console.log(r) does not yet have a value - the database is still processing your request during this time.

The solution to this is one of two major ways:

  • Refactoring your code so that the result is only needed after you are sure that the database request is completed,
  • Utilising the async/await syntax (or, at a broader scale, Promises in general) to be sure that the request is completed during the execution of your program. You can read more about this here
Sodex234
  • 105
  • 1
  • 8
0

Same behavior caused by asynchronous nature of JavaScript. Node.js start an asynchronous operation (such as DB call), but in unlike the synchronous languages (such PHP) not waiting to result, but continue to next operation (last console.log in your case).

For convert operations order to serial I can advice to use Promise construction:

new Promise((resolve, reject) => {
    conn.query('select * from table', (err,result,fields) => {

       if (err) reject(err);

       console.log(result); // It works.
       resolve(result);
    });
})
.then(result => {
    // output will be after query done
    console.log(result);
})
.catch(error => {
    // something went wrong :(
    console.error(error);
});
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39