0

I have code written

function getDetails (req, res) {
    const dbQuery = `call spGetSLAReportsDetails('${req.body.domainId}', ${req.body.days},'${req.body.type}','${req.body.app}')`
    try {
      connectDatabase(dbQuery).then((rows) => {
        if (!_.isEmpty(rows.dbData) && !_.isEmpty(rows.dbData[0])) {
          const resultList = []
          rows.dbData.pop()
          var bar = new Promise((resolve, reject) => {
            rows.dbData[0].forEach((element, index, array) => {
              let query = `select * from YCW.YWFWIC  ic where ic.witem=${element.witem} and ic.reqno=${element.reqno};`
                connectDatabase(query).then((data) =>{
                  for (var i = 0; i < data.dbData.length; i++) {
                    element[data.dbData[i]["cfield"]] = data.dbData[i]["cvalue"]
                }
                resultList.push(element)
                // console.log(resultList)
                }).catch((err) => {
                  console.log(err)
                })
                if (index === array.length -1) resolve();
            });
        });

        bar.then(() => {
          console.log(resultList);
      });
          res.status(msgCodeJson.ERR004.code).send({
            result: resultList })
        } else {
          console.log("empty array")
          res.status(msgCodeJson.ERR004.code).send({
            message : "No data found"
          })
          // httpResponseHandlerError(res, msgCodeJson.ERR001.code, msgCodeJson.ERR001.msg)
        }
      }).catch(() => {
        httpResponseHandlerError(res, msgCodeJson.ERR002.code, msgCodeJson.ERR002.msg)
      })
    } catch (err) {
      httpResponseHandlerError(res, msgCodeJson.ERR009.code, msgCodeJson.ERR009.msg)
    }
  }

  module.exports.getDetails = getDetails

i want data to be fit in resultlist but i get empty list after all operation. while in foreach loop i am getting proper output. kindly help in issue. i tried with async foreach loop but some syntax error is coming. kindly help

1 Answers1

0

as mentioned in the comment of the code you're using Best way to wait for .forEach() to complete

This is OK if there is no async processing inside the loop.

yet you have an async function inside your forEach callback, namly this:

connectDatabase(query).then((data) => {
    for (var i = 0; i < data.dbData.length; i++) {
        element[data.dbData[i]["cfield"]] = data.dbData[i]["cvalue"]
    }
    resultList.push(element)
}).catch((err) => {
    console.log(err)
})

you'll need to resolve the "outer/parent" promise from inside the "inner/child" promise


I suggest using a regular good old for loop and/or checking the count of resolved promises against the rows.dbData[0].length and calling a final code/function once they match

Maher Fattouh
  • 1,742
  • 16
  • 24