Good day! I can not figure out how to return the result of a SELECT from the callback function query. The point is this: there is a server on node.js which receives POST requests from the client and accordingly performs certain actions with the mysql database. With the record and the update in the database figured out - everything works. But I cannot understand how to return selection on selection from the table in base. For clarity, I will give part of the code:

// Здесь идет функция обработки POST-запроса function accept(req, res) { if (req.method == "POST") { var requestBody = ''; req.on('data', function(data) { requestBody += data; }); req.on('end', function() { var formData = qs.parse(requestBody); var login = formData.login; //Далее нужно проверить существование записи в БД //и если такой нет то сделать новую запись в БД, иначе обновить существующую selectDB(login); // Здесь нужно получить результат чтобы запустить условие if (selectDB(login)) ... updateDB(login,score); else insertDB(login,score); .... }); // И есть некая функия selectDB function selectDB(param1) { var connection = mysql.createConnection({ host : '', user : '', password : '', database : '' }); connection.connect(); connection.query( {sql: 'SELECT * from users where login = ?', values: [param1] }, function(err, results, fields) { if (err) return err; // console.log(results) - возвращает результат выполения запроса в БД, но return results - возвращает undefined return results; } ); connection.end(); } 

How do I get function selectDB in function accept? I apologize for the stupid question - with the java script so far on you and I do not understand many things. I suppose connection.query returns an object, but I looked at its output in the node.js console and did not find a method in it that returns the result of the callback function.

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Need asynchronous logic with a callback function:

A small example:

  function accept(req,res){ // ... // ждем ответа <-- selectDB(filter,function(results){ res.render('index',{ rows: results || [] }) }); } // функция обратного вызова вторым аргументом function selectDB(param1, callback){ // ... connection.query( {sql: 'SELECT * from users where login = ?', values: [param1] }, function(err, results, fields) { if (err) return err; // --> callback(results); } ); } 

Also, do not forget to use the async library for complex asynchronous constructions.

  • Thank you very much - I will understand. - Nikolay
  • Explain to the uninformed please what is going on here res.render ('index', {rows: results || []}) - Nikolay
  • caught up with everything - thanks again! :) - Nikolay