一段时间以来,我一直在努力兑现诺言,但我还没有找到解决问题的办法。
我想做什么;
我正在从MongoDB中获取汇总数据,并将其值分配给类对象。 这是聚合的一部分;
static get(email: BaseUser['email']) {
const query = { email: email }
return new Promise(resolve => {
const data = this.model.aggregate([
{
$match: query
}, {
$project:
{ // Get the last element of the array which is previous week's data
d1: { $arrayElemAt: ["$data.myData1", -1] },
d2: { $arrayElemAt: ["$data.myData2", -1] },
d3: { $arrayElemAt: ["$data.myData3", -1] },
email: email
}
}
])
resolve(data)
})
}
在这里我要调用上面的函数;
private static async set(email: string) {
console.log(1)
const data = await MongooseBusiness.get(email); // below code won't work
console.log(data, 'data')
const oldCumulativeCounts = data[0];
console.log(4)
return new Promise(resolve => resolve('a piece of data'));
}
就像我在上面的注释中所说的那样,等待后的代码无法正常工作。好像还没有。即使我在get
函数中解决了诺言。有帮助吗?
答案 0 :(得分:0)
据我所知,this.model.aggregate()
返回了Promise,这意味着您的方法get
返回了Promise<Promise<...>>
。
您可以简单地返回this.model.aggregate()
而不是new Promise
:
static get(email: BaseUser['email']) {
const query = { email: email }
return this.model.aggregate([
{
$match: query
}, {
$project:
{ // Get the last element of the array which is previous week's data
d1: { $arrayElemAt: ["$data.myData1", -1] },
d2: { $arrayElemAt: ["$data.myData2", -1] },
d3: { $arrayElemAt: ["$data.myData3", -1] },
email: email
}
}
])
}