I'm trying to execute a query to a mysql database after getting some ids from another query, but it sends me the callback
blank, so it responds before finishing the query to the bd I do not know how to solve it.
imgmodule.darImagenesServ = (row,callback)=>
{
if(connection)
{
console.log('antes del ciclo');
for (var i = 0; i < row.length; i++)
{
console.log('en el ciclo');
var serv = row[i];
var id = serv.idservicios;
var sql = 'SELECT * FROM fotos where servicios_idservicios = ?';
connection.query(sql,[id],(err,resp)=>
{
console.log(id);
row.fotos = resp;
//codigo que crga la nueva consulta al json row
});
}
callback(null,row)
}
};
Change the code for this
if(connection)
{
var sql = 'SELECT servicios.* FROM servicios ORDER BY calificacion asc;';
connection.query(sql,(err,row)=>{
if(err)
{
}
else
{
var p =0;
return new Promise((resolv,reject)=>{
var sql = 'SELECT * FROM fotos where servicios_idservicios = ?';
var jsonServ = [];
for (var i = 0; i < row.length; i++)
{
var serv = row[i];
console.log(i);
id = serv.idservicios;
connection.query(sql,[id],(err,resp)=>{
console.log('consulta bd');
if(err){throw err}
else {
serv.foto = resp;
//console.log('///////*****///////');
console.log(serv);
jsonServ.push(serv);
p++;
if(p==row.length)
{
band=true;
console.log('final ciclo');
if(band==true)
{
//resolv(jsonServ);
callback(null,jsonServ);
}
}
}
});
}
});
}
});
}
console.log('prueba');
};
and it makes the cycle first and then the query to the database gives a result like this:
servicios
prueba
0
1
2
3
4
5
6
7
8
9
10
11
12
13
consulta bd
RowDataPacket {
idservicios: 15,
nombre: 'fotos fots y mas fotos',
descripcion: 'prueba de fotos',
duracion: 25,
max_citas_ves: 2,
video: 'http://www.youtube.com//ashd89u98',
calificacion: 3,
provedores_id: 1780508912002126,
municipio_id_municipio: 13301,
foto: [] }
consulta bd
RowDataPacket {
idservicios: 15,
nombre: 'fotos fots y mas fotos',
descripcion: 'prueba de fotos',
duracion: 25,
max_citas_ves: 2,
video: 'http://www.youtube.com//ashd89u98',
calificacion: 3,
provedores_id: 1780508912002126,
municipio_id_municipio: 13301,
foto: [] }
consulta bd
RowDataPacket {
idservicios: 15,
nombre: 'fotos fots y mas fotos',
descripcion: 'prueba de fotos',
duracion: 25,
max_citas_ves: 2,
video: 'http://www.youtube.com//ashd89u98',
calificacion: 3,
provedores_id: 1780508912002126,
municipio_id_municipio: 13301,
foto:
[ RowDataPacket {
id: 4,
nombre:
'IMG_20171129_163708_resized_1jpgGjkotBxnr4CadtxGMS0C4esy.jpg',
ruta:
'/servicios/IMG_20171129_163708_resized_1jpgGjkotBxnr4CadtxGMS0C4esy.jpg',
servicios_idservicios: 12 } ] }
consulta bd
This is the query with the last id you take in the cycle.