Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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://api.openweathermap.org/data/2.5/weather?lat=${item.latjson}&lon=${item.lonjson}&appid=${api_key}&units=metric&lang=sp`;
    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[^]
Posted
Updated 14-Dec-21 9:57am
v2
Comments
0x01AA 14-Dec-21 14:06pm    
Without diving into your code, your statement
"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"

tells me you are closing your connection to the db after insert....
martnjf 14-Dec-21 14:08pm    
@0x01AA yes, but how can I close it properly in that case? I'm kind of new using Tedious and Node JS
0x01AA 14-Dec-21 14:12pm    
And I know 0 from Tedius. I would guess (very wild guess) to put connection.close() after the loop. But better be patient, I think somebody who knows it better will help sooner or later ;)
martnjf 14-Dec-21 14:13pm    
I'll try and wait, thanks mate :)
0x01AA 14-Dec-21 14:30pm    
For a first dirty trial simply comment out connection.close(). If this helps you can investigate more for a clean solution ;)

1 solution

 
Share this answer
 
v2
Comments
martnjf 14-Dec-21 16:32pm    
This examples do not fit in mine

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900