Loop without repeating Nodejs + mysql data?

Asked

Viewed 404 times

0

I need to insert the DESCRIPTION field into a CATEGORY table;

I have my data in JSON format (already on the server);

My loop runs the sequence of steps:

  1. Checks whether the "category" field exists in the JSON object
  2. Performs SELECT to see if the data already exists in the database

    SELECT * FROM CATEGORIA WHERE DESCRICAO = '${categoria}' ORDER BY ID_CATEGORIA ASC LIMIT 1

  3. If the resultset returns something it takes the 1° ID_CATEGORIA found, IF IT DOES NOT enter the category in the database

    INSERT INTO categoria(descricao) VALUES ('${categoria}')

  4. Go back to step 1 until the JSON objects are finished

The problem is that when I insert a JSON the loop runs completely (i.e., all objects), including SELECT works normally 1 by 1, but only after the finished loop does it execute the INSERT queries.

When I enter the next JSON that already has registered CATEGORY it does not perform INSERT, but stores my ID_CATEGORIA in a variable as expected, usually.

I cannot enter repeated categories in the bank, this is one of the situations that use recursiveness, but I will also use for others like CITY, which also can not have repeated...

I’ve tried several loop structures, e.g., for, for...of, foreach(), and libs like Sync-each, Sync, and a few more, but all only insert the data after the finished loop (even if the Insert query is inside the loop).

NOTE: I am using querystring and mysql lib inside an HTTP server

req.on('data', function (data) {
                objJson = JSON.parse(data)

                popularDados(0);

                // Função recursiva para inserir dados no banco
                function popularDados(x) {
                    if (x < objJson.objetos.length) {

                        // Populando categoria
                        processarCategoria(objJson.objetos[x]);

                        function processarCategoria(atualObjeto) {[...]}

                        popularDados(x + 1)
                     }
                };

})  



UPDATE 04/09/2018

I solved my problem for now, passed the function to the front and now I do X post via ajax, where x is the number of objects of my JSON:

client-side:

function popularDados(x) {
        if (x < objetos.length) {

            var sendObject = objetos[x];

            $.ajax({
              url: "server.js",
              method: "POST",
              dataType: "Json",
              data: JSON.stringify({
                  objeto : sendObject
              })
            })
              .done(function( obj ) {

                // Usando setTimeout() apenas para visualizar no console
                setTimeout(function(){

                    popularDados(x + 1);

                }, 400);

            })
              .fail(function( jqXHR, textStatus ) {
                alert( "Request failed: " + textStatus );
            });          
        }
}

server-side:

req.on('data', function (data) {

        objJson = JSON.parse(data)

        // Visualizando o dado da chave "categoria" no console
        console.log('\nCategoria : ' + objJson.objeto.categoria)


        processarCategoria(objJson.objeto);

        function processarCategoria(atualObjeto) {[...]}

    })
  • 1

    Good afternoon. At querystring, you created a promise (Promise) for her?

  • Good afternoon, I didn’t create, I read these two articles: link link But I couldn’t adapt in my code :/ ?

  • 1

    I created a gits to demonstrate how you are using the query with Promise, see if you can understand . PROMISE The use of Promise for database query is important, because the nodejs is asynchronous and calls to banks are always last in the execution of cogido, it does this because it knows that the calls consume an extra time in the execution. And by generating the promise you force the No to perform the insertion not order you set.

  • 1

    In this example I also made use of async/await, separated the promise into a function and then made the second async function and made the execution await the return of the promise (await). This way the last.log seal will not be Undefined.

  • I appreciate your support @Andersonmendes , but this solution, as well as the others that I tried and the one that is implemented (referring to SELECT) work perfectly, but when doing an INSERT query it did not respect the promise, as well as the other attempts performed the INSERT at the end.. :/

  • Um I understand, I will perform some test with something similar that you have and then I warn the result.

  • @Andersonmendes , I solved the problem I was, I migrated the recursive function to the front, I did it with the object still in front sending 1 object at a time, ie, 1 post ajax at a time, and BAZINGA!! Do not enter any more repeated data... I really thank you for your help, now I understand Promise! Hug :)

  • Opa que bom, pior que eu não realizei o test com recursividade e Promise, mas vou, quero saber o comportamento das Promises com recursão.

Show 3 more comments

1 answer

0


RESPONDING WITH UPDATE 04/09/2018 TO LEAVE QUESTION AS SOLVED

I solved my problem for now, passed the function to the front and now I do X post via ajax, where x is the number of objects of my JSON:

client-side:

function popularDados(x) {
    if (x < objetos.length) {

        var sendObject = objetos[x];

        $.ajax({
          url: "server.js",
          method: "POST",
          dataType: "Json",
          data: JSON.stringify({
              objeto : sendObject
          })
        })
          .done(function( obj ) {

            // Usando setTimeout() apenas para visualizar no console
            setTimeout(function(){

                popularDados(x + 1);

            }, 400);

        })
          .fail(function( jqXHR, textStatus ) {
            alert( "Request failed: " + textStatus );
        });          
    }
}

server-side:

req.on('data', function (data) {

    objJson = JSON.parse(data)

    // Visualizando o dado da chave "categoria" no console
    console.log('\nCategoria : ' + objJson.objeto.categoria)


    processarCategoria(objJson.objeto);

    function processarCategoria(atualObjeto) {[...]}

})

Project repository: https://github.com/JhowRaul/Imobiliaria-BI

Browser other questions tagged

You are not signed in. Login or sign up in order to post.