Asynchronous nature of nodejs, loop for com querie mysql

Asked

Viewed 90 times

1

Inside an upload route in the nodejs I have it:

router.post('/uploads',function(req,res){  
    //Omitido algumas instruções para melhorar o entendimento.
    InsereMidia = function(midia){
        ExisteMidia(midia,function(midias_linhas){
            if(midias_linhas == 0){
                //AdicionarMidia(midia);        
            }else midia_repetida[midia_repetida.length] = path_arquivo[i];
        }); 
    }           

    if(rows[0].contador == 0){ 
        AdicionarAlbum(galeria,function(album){             
            midia = { 'id_usuario' : sess.id_usuario,'album' : album.insertId, 
            'titulo' : conv.decode(titulo, 'latin-1') };
            for(var i=0;i<path_arquivo.length;i++){ 
                midia.path_arquivo = path_arquivo[i];
                InsereMidia(midia);
            }
        });
       }else ....

I upload images to the server, and clicking a button in my form passes several values (title, user id, album id and file path). The above routine works perfect, the problem is at the time I call the function ExisteMidia:

ExisteMidia = function(midia,cb){ 
    // O objeto json midia contendo informações dos arquivos do upload é 
    //recebido até aqui corretamente.
    pool.getConnection(function(err,connection){
        connection.query("SELECT COUNT(ID_MIDIA) AS contador FROM MIDIA 
            WHERE PATH_ARQUIVO='"+midia.path_arquivo+"'",function(err,rows){
            if(err) throw err
            cb(rows[0].contador);   
            connection.release();   
        });
    }); 
}

However after pool.getConnection, only the last midia object of my loop interaction for is sent. That is; the select that would be to check if there was the insertion of the file later, does not work because it will check repeatedly for the last value of the object sent by parameter.

An example to try to clear up this confusion a little before pool.getconnection:

{ id_usuario: 94,
  album: 46,
  titulo: 'Foto1',
  path_arquivo: '/uploads/tmp/fotos/94/teste1.jpg' }
{ id_usuario: 94,
  album: 46,
  titulo: 'Foto2',
  path_arquivo: '/uploads/tmp/fotos/94/teste2.jpg' }
{ id_usuario: 94,
  album: 46,
  titulo: 'Foto3',
  path_arquivo: '/uploads/tmp/fotos/94/teste3.jpg' }

After pool.getconnection:

{ id_usuario: 94,
  album: 46,
  titulo: 'Foto3',
  path_arquivo: '/uploads/tmp/fotos/94/teste3.jpg' }
{ id_usuario: 94,
  album: 46,
  titulo: 'Foto3',
  path_arquivo: '/uploads/tmp/fotos/94/teste3.jpg' }
{ id_usuario: 94,
  album: 46,
  titulo: 'Foto3',
  path_arquivo: '/uploads/tmp/fotos/94/teste3.jpg' }

I know this is the asynchronous nature of language, but what’s the right approach to solving it?

I have only one month of programming in nodejs. Any advance or comment would be of great help.

No answers

Browser other questions tagged

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