javascript - 完成foreach循环后如何在节点js中返回推送的数组响应?
问题描述
我正在运行一个 foreach 循环并尝试将数据发送到客户端。但是当它从循环中出来时,它给出了空数组,因为我已经全局声明了变量。我想单独推送loanid并将其作为响应返回这是我的代码片段
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: "消息发送成功", invalidLoanID : invalidLoanID
解决方案
尝试使用异步/等待。
基本上,当您使用 .then() 处理 Promises 时,您的代码不会等待您的 Promise 被解析。然后,您的代码在“res.status(200).send...”之前传递,并且在您的 Promise 在您的 .then() 中解决之后
使用 async/await 你可以“强制”你的代码等待这个 Promise 被解决。
推荐阅读
- python - Python 整理出一个复杂的字典
- c++ - 准确的睡眠/等待。视窗操作系统。1毫秒。准确性
- java - Java Web 客户端远程连接
- antlr - ANTLR tokenVocab 中的相对路径
- postgresql - 在 Postgreql 中,如何确定 postgres 表中的列是否为 LOB 类型,然后如何找到模式中最大 LOB 值的大小?
- json - 为什么我得到更新的 json 字段转换的信息 ZoneAwarePromise 数据
- flutter - 如何在一个选项卡中向另一个选项卡显示/隐藏浮动操作按钮?
- javascript - 身体和图像的大小差异
- python - 在同一行上的 pytorch-ignite ProgressBar 上编写验证指标
- flutter - Navigator of 和 Navigator pop 的区别