如何映射JavaScript数组以将每个元素保存到数据库并返回保存的项



我正在开发一个应用程序,该应用程序允许用户向联系人列表发送电子邮件。以下是我遇到问题的功能的工作原理:

  • 电子邮件内容将保存到数据库中
  • 联系人阵列已映射。对于每个联系人
  • 。。。联系人将保存到数据库中
  • 。。。将向联系人发送一封电子邮件,其中包含数据库生成的电子邮件id及其联系人id的URL
  • 。。。保存的收件人应该返回,但当前未返回
  • 保存的联系人数组当前只是空对象:(返回到前端

每个联系人都会返回一个空对象,而不是实际联系人,这很奇怪,因为我可以在地图中console.log()该对象,并且联系人的信息正在电子邮件中发送,所以它肯定在某个时候存在。

这是代码:

const postOne = async (req, res) => {
const db = req.app.get("db");
const { adviceRequest, recipients } = req.body;
// ( Validation goes here )
try {
// Save the request.
let [savedRequest] = await db.requests.postOne([
adviceRequest,
req.session.user.id,
]);
// For every recipient...
let savedRecipients = recipients.map(async (person) => {
// ...Save them to the database.
let [savedRecipient] = await db.responses.postOne([
savedRequest.request_id,
person.email,
person.name,
req.session.user.id,
]);
// At this point, console.log(savedRecipient) shows the actual recipient, so it works.
// ...Send them an email.
await sendMail(savedRecipient, savedRequest);
// ...Then add the saved recipient to the array that .map() generates.
return savedRecipient;
});
// Send the request and the array of people back.
return res.status(200).json([savedRequest, savedRecipients]);
} catch (err) {
return res.status(500).json(err);
}
},

问题是,.map()返回的数组是一个空对象数组。我不知道为什么。在.map()内部,savedRecipient被定义为它应该是的,并且那里的信息被成功地用于通过电子邮件发送所需的信息。但返回到前端的是一组空对象——每个联系人一个。

如果有人能告诉我我做错了什么,我将不胜感激!

您可以尝试让循环使用异步和等待。

let savedRecipients = recipients.map(async (person) =>

属性savedRecipients这里是一组promise。试着解决这个承诺,像这样:

const savedRecipientsData = await Promise.all(savedRecipients);

最新更新