3 回答

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); });
});

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);
});

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);
添加回答
舉報