E
E
ebanytiu_lis2017-06-15 15:48:33
MySQL
ebanytiu_lis, 2017-06-15 15:48:33

How to make Node.Js wait for MySQL to execute?

Because Node.js, unlike PHP, is an asynchronous thing, then some difficulties arise ...

function sql_get(){
  var mysql      = require('mysql');
  var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : '1047750'
  });
  connection.query(
    'SELECT * FROM test',
    function(err, result, fields){
      return(result[0]);
    }
  );
  
  connection.end();
}
console.log(sql_get());

The code prints "undefined" to the console...
ATTENTION, QUESTION! How to make Node wait for a response from MySQL, and then print the value to the console?
Do not send to Google! It hasn't given me anything other than a headache...

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
Serezha, 2017-06-15
@ebanytiu_lis

And if so:

var mysql      = require('mysql');
  var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : '1047750'
  });
  connection.query(
    'SELECT * FROM test',
    function(err, result, fields){
      console.log(err);
      console.log(result);
    }
  );
  
  connection.end();

So you have a callback here, a function that will be called after the request is made and will accept data (result or error).

O
Oleg Gamega, 2017-06-15
@gadfi

use async await

A
Alexander Drozdov, 2017-06-15
@bagzon

Download bible sync
https://github.com/ybogdanov/node-sync

B
Boris Korobkov, 2017-06-15
@BorisKorobkov

The function sql_get()has no return, so "undefined".
returnin a completely different function. By the way, it is not used in any way. Instead, write a call to the action you need (for example, console.log(result);).
Forget about PHP and synchronicity. If you started writing on node.js - learn asynchrony!

A
Alexander N++, 2017-06-15
@sanchezzzhak

await from ES6 sends you hello
caolan.github.io/async
better pseudo async and getting rid of callback sausage

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question