Search code examples
javascriptmeteorasync-await

Is using Promise.await instead of async/await correct?


When performing some new operations in my project, I learned that db.aggregate should be executed asynchronously:

db.aggregate(
                        [
                            {
                                $match: { "records": { $exists: true, $ne: NaN } }
                            },
                            {
                                $group: { _id: "$recordkey", _avg: { $avg: "$records" } }
                            }
                        ]
                    ).toArray());

I could not change the calling code to async but I found that simply wrapping the function above into Promise.await()will work. Is this a correct way that I can use? I do not really get how exactly it works.


Solution

  • Yes, you can use Promise.await() to make the db.aggregate() function call asynchronous.

    Promise.await() is a function that allows you to wait for a promise to resolve before continuing with the execution of the function. When you call Promise.await() on a promise, the function will wait for the promise to resolve or reject before continuing with the execution of the code.

    In your case, calling db.aggregate() returns a promise, and you want to wait for the promise to resolve before continuing with the execution of your code. By using Promise.await() on the db.aggregate() call, you are telling the function to wait for the promise to resolve before moving on to the next line of code.

    That's how it works ^_^