Answer the question
In order to leave comments, you need to log in
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());
Answer the question
In order to leave comments, you need to log in
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();
The function sql_get()
has no return
, so "undefined". return
in 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!
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 questionAsk a Question
731 491 924 answers to any question