How to return pushed array response in node js after completing the foreach loop?

Viewed 50

I am running one foreach loop and trying to send the data to the client. but when its coming out from the loop its giving empty array since i have declared variable globally. i want to push the loanid separately and return it as a response here is my code snippet

if (notificationType == "sms" || notificationType == "both") {
  let invalidLoanID = [];
  let text = ""
  notificationPayload.forEach((element) => {
    let checkQuery =
      "select * from loan where loanid = " + "'" + element.loanid + "'";
    sql
      .query(checkQuery)
      .then((loanResponse) => {
        // console.log("------",loanResponse)
        if (loanResponse.length == 0) {
          text = element.loanid
          invalidLoanID.push(text);
          console.log("===", invalidLoanID);
        }
        if (loanResponse.length > 0) {
          let insertQuery =
            "INSERT INTO notification " +
            "(loanid, userid, language, notificationmsg, createddt, expirydt, " +
            "notificationtype, isFailed, failureremarks,isSMSSent) VALUES " +
            "(" + 
            "'" +
            element.loanid +
            "'," +
            "'" +
            element.userid +
            "'," +
            "'" +
            element.langauge +
            "'," +
            "'" +
            "Loan no:"+ element.loanid +"; " + element.notificationMsg +
            "'," +
            "'" +
            element.createdate +
            "'," +
            "'" +
            element.expiryDate +
            "'," +
            "'" +
            element.notificationType +
            "'," +
            +element.isFailed +
            ", '" +
            element.failureremarks +
            "', 0" +")";
        }
      })
      .catch((err) => {
        res.status(400).json({
          status: 400,
          message: err,
        });
      });
      }) 
  })
}

res.status(200).send({ response: "Success", message: "Message sent sucessfully", invalidLoanID : invalidLoanID

2 Answers

Try to use async/await.

Basically, when you work with Promises using .then(), your code doesn't wait your Promise to be resolved. Then, your code is passing before by "res.status(200).send..." and after your Promise is resolved in your .then()

Using async/await you can "force" your code wait this Promise to be resolved.

you can try

sql
  .query(checkQuery)
  .then((loanResponse) => { 
   ...... **your code** ......
    res.status(200).send({
    response: "Success",
    message: "Message sent sucessfully",
    invalidLoanID : invalidLoanID

  })  }).catch((){})

your response code resolve first ,it wont be wait query.then()

Related