【发布时间】:2021-08-21 23:49:13
【问题描述】:
我有一个高级 Mongo 查询。
我尝试计算多个字段的不同值。
首先我必须遍历三个值,它们是我的 Mongoose 架构中的条目,然后我必须计算每个相应字段的每个不同值,并将它们作为字符串返回。
const mappedStuff = this.featureFields.map(async field => {
return new Promise(async (resolve, reject) => {
const distinctValues = await this.gameModel.distinct(field);
return distinctValues.map(async entry => {
console.log(
`${field}, ${entry}, ${await this.gameModel.count({
[field]: entry,
})}`,
); //Logs out correct value
resolve(
`${field}, ${entry}, ${await this.gameModel.count({
[field]: entry,
})}` as string, //resolves instantly and does not return the correct value
);
});
});
});
console.log(Promise.all(mappedStuff));
return Promise.all(mappedStuff);
console.log 工作正常,我只想返回该值,我尝试将其推送到外部列表,但不起作用,因为我在字符串中有一个 await。
因此我尝试将整个事情包装在一个承诺中,但这也不能解决问题。有人有解决办法吗
【问题讨论】:
-
你想要的输出是什么?
Promise.all()不会在第二层 Promise 中再次使用Promise.all来深度等待所有 Promise。此外,在 async 函数中创建新的 Promise 是多余的。
标签: typescript mongodb asynchronous promise