0

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.

0 Answers0