How to get results from nodejs using mysql package?

Firstly, I connect db and select DB:

var defaultOptions = { user: "root", pwd:'admin', db:"britcham_dev_local", server:"local", // Maybe we don't need this variable. }; var client = new Client(); client.user = defaultOptions.user; client.password = defaultOptions.pwd; client.connect(function (error, results) { // }); client.query('USE ' + defaultOptions.db, function (error, results) { // }); 

Secondly, I request with the client object:

 var self = this; var this.users; client.query("SELECT * FROM users", function (error, results, fields) { if (error) { // } if (results.length > 0) { self.users = results; } }); console.log(this.users); 

nothing happens ??? Why?

+5
source share
2 answers

Since node.js is not blocking and asynchronous, then in this code:

 client.query("SELECT * FROM users", function (error, results, fields) { if (error) { // } if (results.length > 0) { self.users = results; } }); console.log(this.users); 

data from the database may not yet be loaded into the user variable when you try to log into the console. You can check this if you perform the console.log operation in the request, for example:

 client.query("SELECT * FROM users", function (error, results, fields) { if (error) { // } if (results.length > 0) { console.log(results); } }); 

To pass the result to a variable when the operation is completed, you can associate your client DB call with the function with the callback parameter and set your variable when calling the callback, for example:

 function query(sql, callback) { client.query(sql, function (error, results, fields) { if (error) { // } if (results.length > 0) { callback(results); } }); } query("SELECT * FROM users", function(results) { self.users = results; console.log(self.users); }); 

The code above is just a concept.

+7
source

How does this answer differ from this?

 var self = this; var this.users; client.query("SELECT * FROM users", function (error, results, fields) { if (error) { // } if (results.length > 0) { self.users = results; console.log(this.users); } }); 

Perhaps I'm wrong, this does not differ from the proposed answer in that it writes to the console no earlier than when we have data from the database.

Does the proposed answer seem to be just adding another function?

0
source

Source: https://habr.com/ru/post/986113/


All Articles