微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

完成foreach循环后如何在节点js中返回推送的数组响应?

如何解决完成foreach循环后如何在节点js中返回推送的数组响应?

我正在运行一个 foreach 循环并尝试将数据发送到客户端。但是当它从循环中出来时,它给出了空数组,因为我已经全局声明了变量。我想单独推送贷款 ID 并将其作为响应返回,这是我的代码片段

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({ 回复: "成功",message: "消息发送成功",invalidLoanID : invalidLoanID

解决方法

尝试使用 async/await。

基本上,当您使用 .then() 处理 Promise 时,您的代码不会等待您的 Promise 得到解决。然后,您的代码在“res.status(200).send...”之前通过,在您的 Promise 在您的 .then() 中解决之后

使用 async/await 你可以“强制”你的代码等待这个 Promise 被解决。

,

你可以试试

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

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

您的响应代码首先解析,它不会是等待查询。然后()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。