如何在Node js完成foreach循环后返回推数组响应?



我正在运行一个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 ({回应:"Success",消息发送成功,invalidLoanID: invalidLoanID

尝试使用async/await。

基本上,当你使用.then()处理Promise时,你的代码不会等待Promise被解析。然后,你的代码通过"res.status(200).send…"在你的。then()

中解析你的Promise之后使用async/await你可以强制执行你的代码等待这个Promise被解析。

你可以试试

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

最新更新