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
1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.