Hello,
Is it possible to do synchronous queries ?
Because I want to use a script that will request the database if a table exist. If not, then it will create the table.
But because of asynchronous mode, this doesn't work properly.
Thanks for your help !
hi @flexbrane can you post your code? What you are describing can be achieved very easily with async flow
I'm just starting to working NodeJS (and learning by the way).
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : '<user>',
password : '<password>',
database : '<project>'
});
var tableExist = 0;
connection.connect();
//
// Try to determinte if table 'product' exist
//
connection.query("\
SELECT * FROM product;", function(err, rows, fields) {
if (err != null) {
console.log('Table doesn\'t exist');
tableExist = 0;
}else {
tableExist = 1;
//console.log(rows);
console.log('Table exist !');
}
});
//
// If table 'product' doesn't exist, we create it
//
if(tableExist == 0){
connection.query("CREATE TABLE IF NOT EXISTS `product`", function(err, rows, fields) {
if (err) throw err;
console.log('Table created');
});
[...]
//
// Close the connection
//
connection.end();
the closest to your original code with changes to use reply from first query in the second:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : '<user>',
password : '<password>',
database : '<project>'
});
var tableExist = 0;
connection.connect();
//
// Try to determinte if table 'product' exist
//
connection.query("\
SELECT * FROM product;", function(err, rows, fields) {
if (err != null) {
doStuffAfterDetectingTable(0);
}else {
doStuffAfterDetectingTable(1);
}
});
function doStuffAfterDetectingTable(tableExist) {
//
// If table 'product' doesn't exist, we create it
//
if(tableExist == 0){
connection.query("CREATE TABLE IF NOT EXISTS `product`", function(err, rows, fields) {
if (err) throw err;
console.log('Table created');
});
[...]
//
// Close the connection
//
connection.end();
}
Ok, so if I understand correctly, it's asynchronous queries, by using functions instead of multiples queries like my previous code ?
Thank you very much :)
It seems that you have made a mistake :
doStuffAfterDetectingTable(tableExist) {
Should be :
function doStuffAfterDetectingTable(tableExist) {
Without function my code doesn't work.
yes, because side effect of most async functions can be thought as "please put this task to queue" there is no "return value" in traditional function call sense. Instead, together with your input you put reference to a function ( "continuation" ) which is called when result is available
Most helpful comment
the closest to your original code with changes to use reply from first query in the second: