Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
Make a callback function wait for the db call to finish

I am making a series of DB calls based on the response from the first DB call. In the end, I am looping through the combined result and making the response. when I am running this code, I found for each callback function is not waiting for the response to complete. it is looping through the result from the first DB call. here is my code

this.router.get("/:version/:dept/:id", (req: any, res: any) => {
      try {
        logger.trace("getDetails call initialized");
        const dept= req.params.dept;
        const id= req.params.id;
        const deptDao = new deptDAO();
        let finalDetails = [];
        let simpleDetail = {};
        deptDao
          .getdetails(dept, id)
          .then((rows) => {
            rows.forEach(async (row: any) => {
              if (row.dept_name== "Science") {
                console.log('Logging error');
                try {
                  let idDao = new IDDao();
                  await idDao .getIdDetails(dept, row.valueId).then((result) => {
                    if (result[0].std_details!= undefined && result[0].std_details.datas != undefined) {
                      row.datas = result[0].std_details.datas;
                    }
                    })
                } catch (error) {
                  logger.error('failed', error);
                }
              } else {
                CommonUtil.formatDetails(dept, rows);
              }
            });
            rows.forEach((dets) => {
              if (row.dept_name== "Science") {
                simpleDetails = dets;
              } else {
                finalDetails.push(dets)
              }
            })
            res.status(200);
            
          })
          .catch((err) => {
            res.status(500);
            res.send({ status: "failed with an error", message: err });
          })
          .finally (() => { res.send({ status: "success", depts: finalDetails, dept: simpleDetails }) });
      } catch (ex) {
        res.status(500);
        res.send({ status: "failed", message: ex });
      }
    });

when this rows.forEach((dets) callback is running, I am not able to get the datas value from the getIdDetails result as it was executed after my response got printed. Could anyone help me with this? I think the promise might help out. but I am not sure of that either.

about 4 years ago · Santiago Gelvez
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda