1 回答
TA贡献1827条经验 获得超8个赞
首先,Users.find()是异步操作,因此oldUsers始终是不确定的。您需要使用await它(如果您没有使用Promise,则必须使用回调)。
const oldUsers = await Users.find(...)
其次,您的notifyOldUsers函数不是异步的,因此它运行映射函数,但是会立即退出,而不是等待映射的异步操作完成。
通常,在映射异步操作时,应使用aPromise.all()收集回调函数返回的所有promise,并等待它们全部解决。
export const notifyOldUsers = async () => {
const promises = oldUsers.map(async (user) => {
await Users.updateOne({ _id: user._id }, { "$set": { isReminded: true }})
await transporter.sendMail(sendMail))
})
return Promise.all(promises)
}
我特意从中拆分了映射,Promise.all()以说明返回的Promise映射。可以进一步优化以下内容。
export const async notifyOldUsers = async () => {
return Promise.all( oldUsers.map(async (user) => {
await Users.updateOne({ _id: user._id }, { "$set": { isReminded: true }})
await transporter.sendMail(sendMail))
}) )
}
在这两种情况下,此异步函数都将返回一个新的Promise,其值将是一个包含整个映射结果的数组。
添加回答
举报