Hi everybody! I'm working in a project in Node JS that takes data from an array, after that it takes data from an array and with that it creates an object with coordinates and weather and other stuff, then saves this object into a DB in SQL Server, I'm doing this using Tedious JS.
The issue I have is that when I try to save data from the array when this only has one object, it works perfectly, but when I add more it shows this error:
Couldn't insert data: Error: Requests can only be made in the LoggedIn state, not the SentClientRequest state
Couldn't insert data: Error: Connection closed before request completed.
What I have tried:
This is what I have tried, as you can see, it read my array in a loop, and does a fetch to create the object to then, insert it into my DB, I have no issues with connecting to my DB.
<pre>function executeStatement1() {
const data2 = [
{
latjson: 21.1236,
lonjson: -101.6737,
idoficina: "1",
},
{
latjson: 21.1236,
lonjson: -101.6737,
idoficina: "2",
}
];
for (let item of data2) {
let url = `https:
fetch(url)
.then((response) => { return response.json();})
.then(function (data) {
var myObject = {
Id_Oficina: item.idoficina,
Humedad: data.main.humidity,
Nubes: data.clouds.all,
Sensacion: data.main.feels_like,
Temperatura: data.main.temp,
Descripcion: data.weather[0].description,
};
const request = new Request(
"EXEC USP_BI_CSL_insert_reg_RegistroTemperaturaXidOdicina @IdOficina, @Humedad, @Nubes, @Sensacion, @Temperatura, @Descripcion",
function (err) {
if (err) {
console.log("No se pudo insertar dato: " + err);
} else {
console.log("Dato con id de Oficina: " + myObject.Id_Oficina + " insertado con éxito.")
}
}
);
request.addParameter("IdOficina", TYPES.SmallInt, myObject.Id_Oficina);
request.addParameter("Humedad", TYPES.SmallInt, myObject.Humedad);
request.addParameter("Nubes", TYPES.SmallInt, myObject.Nubes);
request.addParameter("Sensacion", TYPES.Float, myObject.Sensacion);
request.addParameter("Temperatura", TYPES.Float, myObject.Temperatura);
request.addParameter("Descripcion", TYPES.VarChar, myObject.Descripcion);
request.on("row", function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log("NULL");
} else {
console.log("Product id of inserted item is " + column.value);
}
});
});
request.on("requestCompleted", function () {
connection.close();
});
connection.execSql(request);
});
}
}
this is my question in stackoverflow
javascript - How can I insert multiple data to SQL Server in a loop? using Node JS Tedious - Stack Overflow[
^]