Reputation: 33
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
Upvotes: 0
Views: 159
Reputation: 10163
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);
});
Upvotes: 0
Reputation: 105
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:
result
is only needed after you are sure that the database request is completed,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 hereUpvotes: 1