1 回答

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
首先,Users.find()是異步操作,因此oldUsers始終是不確定的。您需要使用await它(如果您沒有使用Promise,則必須使用回調(diào))。
const oldUsers = await Users.find(...)
其次,您的notifyOldUsers函數(shù)不是異步的,因此它運行映射函數(shù),但是會立即退出,而不是等待映射的異步操作完成。
通常,在映射異步操作時,應(yīng)使用aPromise.all()收集回調(diào)函數(shù)返回的所有promise,并等待它們?nèi)拷鉀Q。
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映射??梢赃M(jìn)一步優(yōu)化以下內(nèi)容。
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))
}) )
}
在這兩種情況下,此異步函數(shù)都將返回一個新的Promise,其值將是一個包含整個映射結(jié)果的數(shù)組。
添加回答
舉報