3 回答

TA貢獻1876條經驗 獲得超6個贊
您錯過了應用于一系列承諾的承諾模式的要點。
Exec將返回一個僅針對數據數組的一個元素進行解析的承諾。因此,您將對數組中的每個數據都有一個承諾,并且您的代碼必須等待所有承諾都得到解決。請記住,這將導致數組中的每個數據執行一次 Mongo 查詢。
最好的方法是將數據數組映射到 Promise 數組,并用于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貢獻1852條經驗 獲得超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貢獻1829條經驗 獲得超13個贊
確保你的函數async前面有關鍵字,你就可以開始了
let count = await Promise.all(
array.map(data =>
userDetailsModel
.find({ UpdateStatusDate: data })
.countDocuments()
.exec()
)
);
consle.log(count);
添加回答
舉報