Inside an upload route in nodejs I have this:
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 on my form is passed several values (title, user id, album id and path of the files). The above routine works fine, the problem is when 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 media object of the interaction of my loop for
is sent. That is; the select that would be to check if the file was inserted 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 this confusion a bit 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 is the correct approach to solve?
I have only one month of programming on nodejs. Any advance or comment would be of great help.