0

I have a MySQL database and I'm working with NodeJS to getting access to it. Here is the code that I'm using to make an INSERT in my table.

var mysql = require('mysql');
var fs = require('fs');
var readline = require('readline');

var ID_User = {value: 0};

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "blah",
  multipleStatements: true
});

function insertNewUser(name_user, password_user) {
    con.connect(function(err) {
        if (err) throw err;

        console.log("Connected!");

        var sql_user = "INSERT INTO `blah`.`User` (`Name`, `Password`) VALUES ('" + name_user + "', '" + password_user + "');"

        con.query(sql_user, function (err, result) {
            if (err) throw err;
            ID_User.value = result.insertId;
            console.log(ID_User);
        });
    });
}

And this is the code that I'm using to execute this function:

console.log("user " + ID_User.value + " " + ID_User);
insertNewUser("user", "123");
console.log("some message");
console.log("user " + ID_User.value + " " + ID_User);

Everything is in the same file, but when I execute the code, this is my output:

the output isn't in order

Why it happens this? How I can control the order of execution of this functions? I tried to put make a second function but this one (insertNewUser()) always is executed until the end.

Thanks beforehand.

Deus Arcana
  • 93
  • 1
  • 1
  • 7
  • Take a look at [this](https://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node) question. – Mika Sundland Dec 10 '17 at 01:01
  • Possible duplicate of [What is the difference between synchronous and asynchronous programming (in node.js)](https://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node) – Scott Stensland Dec 10 '17 at 01:10

0 Answers0