Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda