Answer the question
In order to leave comments, you need to log in
How to assign result of sql query to node.js variable?
You need to assign the result of the query to a variable. Assigning the result of a function to a variable does not work.
I found the following solution on stackoverflow, but it didn't work for me:
connection.query("SELECT * FROM workingProgramOfTheDiscipline", function(err, rows){
if(err) {
throw err;
} else {
setValue(rows);
}
});
let someVar
function setValue(value) {
someVar = value;
console.log('Variable Value: ' + JSON.stringify(someVar)); // нужный результат выводится
}
console.log('Work, please! ' + JSON.stringify(someVar)) // 'Work, please! undefined'
Answer the question
In order to leave comments, you need to log in
function query(sql) {
return new Promise((resolve, reject) => {
connection.query(sql, (err, rows) => {
if (err)
reject(err);
else
resolve(rows);
});
});
}
The query to the database is an asynchronous function. Process the request result either through async / await or through promises
Maybe it will be clearer what the rub is
let someVar; // let someVar = undefined;
setTimeout(() => {
setValue('SOME VALUE');
}, 0);
console.log('Work, please! ' + someVar); // 'Work, please! undefined'
function setValue(value) {
someVar = value;
console.log('Variable Value: ' + someVar); // Variable Value: SOME VALUE
};
console.log('Work, please! ' + someVar); // 'Work, please! undefined'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question