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

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

等待 forEach 從數(shù)據(jù)庫獲取數(shù)據(jù)

等待 forEach 從數(shù)據(jù)庫獲取數(shù)據(jù)

繁花不似錦 2023-09-07 16:54:26
我正在嘗試實(shí)現(xiàn) forEach 從 mongo 數(shù)據(jù)庫獲取數(shù)據(jù)并將每個數(shù)據(jù)推送到數(shù)組。我需要在推送所有數(shù)據(jù)后控制臺記錄該數(shù)組。我嘗試了承諾,但無法得到想要的結(jié)果。這是我所擁有的count=[];array.forEach((data)=>{    userDetailsModel.find({UpdateStatusDate:data}).countDocuments()    .exec((err,data)=>{count.push(data)}) })謝謝你的幫助!
查看完整描述

3 回答

?
HUX布斯

TA貢獻(xiàn)1876條經(jīng)驗 獲得超6個贊

您錯過了應(yīng)用于一系列承諾的承諾模式的要點(diǎn)。


Exec將返回一個僅針對數(shù)據(jù)數(shù)組的一個元素進(jìn)行解析的承諾。因此,您將對數(shù)組中的每個數(shù)據(jù)都有一個承諾,并且您的代碼必須等待所有承諾都得到解決。請記住,這將導(dǎo)致數(shù)組中的每個數(shù)據(jù)執(zhí)行一次 Mongo 查詢。


最好的方法是將數(shù)據(jù)數(shù)組映射到 Promise 數(shù)組,并用于Promise.all等待所有 Promise 解析:


// get an array of promises for each data to query:

let promises = array.map(data => { 

    return userDetailsModel

        .find({UpdateStatusDate:data})

        .countDocuments()

        .exec(); 


});

    

// when all the promises fulfill 

Promise.all(promises).then(counts => {

    console.log(counts);

    // for each counts log the result:

    counts.forEach(result => { console.log(result); });

});


查看完整回答
反對 回復(fù) 2023-09-07
?
慕姐4208626

TA貢獻(xiàn)1852條經(jīng)驗 獲得超7個贊

您可以使用Promise.all()方法在所有承諾之后等待

let count = [];

const promiseArray = array.map((data) => (

? new Promise((resolve) => {

? ? userDetailsModel.find({ UpdateStatusDate: data })

? ? ? .countDocuments()

? ? ? .exec((err, data) => { resolve(data) })

? })

))

Promise.all(promiseArray).then((values) => {

? count = values;

? console.log(count);

});


查看完整回答
反對 回復(fù) 2023-09-07
?
烙印99

TA貢獻(xiàn)1829條經(jīng)驗 獲得超13個贊

確保你的函數(shù)async前面有關(guān)鍵字,你就可以開始了


let count = await Promise.all(

  array.map(data =>

    userDetailsModel

      .find({ UpdateStatusDate: data })

      .countDocuments()

      .exec()

  )

);

consle.log(count);


查看完整回答
反對 回復(fù) 2023-09-07
  • 3 回答
  • 0 關(guān)注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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