P
P
Pavel Kuzmichev2020-12-05 08:48:34
Node.js
Pavel Kuzmichev, 2020-12-05 08:48:34

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'


It is extremely likely that I missed some basic and simple thing due to my own greenness. However, two days I can not find a solution.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Miiinro, 2020-12-06
@Zarb1N

function query(sql) {
  return new Promise((resolve, reject) => {
    connection.query(sql, (err, rows) => {
      if (err) 
        reject(err);
      else
        resolve(rows);
    });
  });
}

V
Vladislav Serebrov, 2020-12-05
@FEAR_Kleef

The query to the database is an asynchronous function. Process the request result either through async / await or through promises

A
Alexei, 2020-12-05
@Azperin

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 question

Ask a Question

731 491 924 answers to any question