即使我解决了对聚合的承诺,也不会在等待后执行等待代码

时间:2020-04-13 13:09:44

标签: node.js typescript mongoose async-await es6-promise

一段时间以来,我一直在努力兑现诺言,但我还没有找到解决问题的办法。

我想做什么;

我正在从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函数中解决了诺言。有帮助吗?

1 个答案:

答案 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
                }
            }
        ])
}