Something strange happens, very strange, the sequence does not end completely, why? this is my code.
First the connection to the bd.
var mysql = require('mysql');
var cnxMysql = function () {
return mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123',
database: 'key'
});
}
exports.cnxMysql = cnxMysql;
The following code I am trying to perform the query.
let objBD = require('../model/cnxMysql').cnxMysql();
for (let i = 0; i < parameters.length; i++) {
for(let x=0; x<Object.entries(parameters[i]).length; x++){
let post;
post = {ID_INTENTO: result, TIPO: Object.entries(parameters[i])[x][0], VALOR: Object.entries(parameters[i])[x][1]};
console.log('111111111111', post);
objBD.query('INSERT INTO PARAMETROS SET ?', post, function (err, rows) {
console.log('22222222222');
});
}
}
The first console is executed first, but it does not enter the second, this is the order of execution.
111111111111 { ID_INTENTO: 197, TIPO: 'error', VALOR: 0.9 }
111111111111 { ID_INTENTO: 197, TIPO: 'lr', VALOR: 0.1 }
111111111111 { ID_INTENTO: 197, TIPO: 'error', VALOR: 0.5 }
111111111111 { ID_INTENTO: 197, TIPO: 'lr', VALOR: 0.1 }
111111111111 { ID_INTENTO: 197, TIPO: 'error', VALOR: 0.1 }
22222222222
22222222222
22222222222
22222222222
22222222222
The ideal sequence would be:
111111111111 { ID_INTENTO: 197, TIPO: 'error', VALOR: 0.9 }
22222222222
111111111111 { ID_INTENTO: 197, TIPO: 'lr', VALOR: 0.1 }
22222222222
111111111111 { ID_INTENTO: 197, TIPO: 'error', VALOR: 0.5 }
22222222222
111111111111 { ID_INTENTO: 197, TIPO: 'lr', VALOR: 0.1 }
22222222222
111111111111 { ID_INTENTO: 197, TIPO: 'error', VALOR: 0.1 }
22222222222
I also modified my code with async await
for (let i = 0; i < parameters.length; i++) {
for(let x=0; x<Object.entries(parameters[i]).length; x++){
let post;
post = {ID_INTENTO: result, TIPO: Object.entries(parameters[i])[x][0], VALOR: Object.entries(parameters[i])[x][1]};
console.log('111111111111', post);
await setParameters(post);
}
}
async function setParameters(post) {
objBD.query('INSERT INTO PARAMETROS SET ?', post, function (err, rows) {
console.log('22222222222', rows);
});
}
But, the result is the same.
rw,
The problem you are having is because of the asynchronous JavaScript.
It's okay that you used 'async/await' to control the synchronization but you are using it incorrectly, the correct way would be:
Where you create the connection you need to be synchronous so that the connection is created and ready to use:
Where you use it to wait for each query you make:
I hope it helps.
All the best