Answer the question
In order to leave comments, you need to log in
How to save the received value from the database response in a global code variable?
How can a database response be made into a variable that will work outside of the function?
var mysql = require('mysql');
var conn = mysql.createConnection({
database: '',
host: "",
user: "",
password: ""
});
conn.connect(function(err) {
if (err) throw err;
});
conn.query("SELECT username FROM Users WHERE id ="+id,
function(err, results, fields) {
console.log(err);
console.log(results[0].username);
});
Answer the question
In order to leave comments, you need to log in
storage.js
const storage = {
users: {},
addOrUpdateUser: function(user) {
this.users[user.id] = user
},
getUserById: function(id) {
if(this.users[id]) return this.users[id]
return null //или [], смотря как у вас принято
}
}
module.exports = storage
var mysql = require('mysql');
const storage = require('./storage')
var conn = mysql.createConnection({
database: '',
host: "",
user: "",
password: ""
});
conn.connect(function(err) {
if (err) throw err;
});
conn.query("SELECT username, id FROM Users WHERE id ="+id,
function(err, results, fields) {
console.log(err);
console.log(results[0].username);
storage.addOrUpdateUser(results[0])
console.log(storage.getUserById(results[0].id))
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question