2

I have a project in Node JS that takes data from an array data2, uses this data to create a object myObject using a fetch with data from an API let url = `https:... and then saves it to a DB in SQL Server, the issue that I'm having is that I followed MS Doc to insert the data, but as I was told here the MS doc's example is for only adding one data, so I decided to reformulate my question, how can I change it to insert all my data? Here is how I do my connection:

var connection = new Connection(config);

connection.on("connect", function (err) {
  if (err) {
    console.log("Failed to connect!!! ", err);
  } else {
    console.log("Successful connection");
    executeStatement1();
  }
});

And here is how I've tried to insert multiple data in a loop:

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);
      });

  }
}

The issue that I'm having is that the code above inserts perfectly data when I have only one object in my data2 array, but when I add more than one I get this messages of errors:

Successful connection
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.

Here I show that when I run the code with only object it works: +

enter image description here

as I was told, I decided to change where I close my connection, but it did not work either, just putting my connection.close(); after my loop:

...
     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);
}

I would like to be able to insert multiple data in the array data2, and if it's possible, to have a little bit of explanation of why my code didn't work and what you changed, thx!

EDIT: I wont give up haha, I continued searching and watch that when I connect:

connection.on("connect", function (err) {
  if (err) {
    console.log("Failed to connect!!! ", err);
  } else {
    console.log("Successful connection");
    executeStatement1();
  }
});

Someone told me that I only run executeStatement1(); once, so it closes the connection and the other part of the array won't be inserted, but doing it in a loop would be fine, right?, I would like to know the correct way to close my connection.

I have reformulated my question here if you have the time I would appreciate if you could check it out

Martín JF
  • 152
  • 2
  • 14
  • 1
    The code connects once but closes the connection after the first `execSql()` completes. Which `execSql()` completes first depends on which remote API call completes first. Perhaps you could restructure the code such that connections are created and used inside your fetch's `then()` methods so that each `execSql()` operates on its own private connection? – AlwaysLearning Dec 09 '21 at 23:53
  • 1
    sorry, this is maybe a fool question but I'm kind of new working with this type of codes, how can I restructure my code and create my connections inside my fetch's? Should I change my ```connection.on("connect", function (err) {``` into my second ```then()``` to start my connection inside my fetch? – Martín JF Dec 10 '21 at 16:00
  • 1
    @AlwaysLearning I kept searching and edited the question, hope you can take a look if you have the time and if it is not a problem for you :) – Martín JF Dec 14 '21 at 19:12

0 Answers0