第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何映射`.find()`返回的數(shù)據(jù)?

如何映射`.find()`返回的數(shù)據(jù)?

繁華開滿天機(jī) 2021-04-06 16:17:21
我有一個簡單的功能:const oldUsers = Users.find(   {      isReminded: false,      creationDate: {         "$lt": new Date(Date.now() - thirtyDays),      },   },);然后:export const notifyOldUsers = () =>    Array.isArray(oldUsers) ? oldUsers.map(async(user, i) => {      await Users.updateOne({ _id: user._id }, { "$set": { isReminded: true }});      await transporter.sendMail(sendMail));   }) : [];};但是問題是oldUsers返回object,如果返回的話console.log,它是一個復(fù)雜的Query對象。問題:如何正確循環(huán).find()產(chǎn)生的數(shù)據(jù)?
查看完整描述

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ù)組。


查看完整回答
反對 回復(fù) 2021-04-22
  • 1 回答
  • 0 關(guān)注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號