Could you help me solve my function get
asynchronously? I have it with promises as follows and it works fine, but I can't do it in the await way, which is the second one.
router.get("", (req, res, next) => {
const paginaSize = +req.query.pagesize;
const paginaActual = +req.query.page;
const perfilQuery = Perfil.find();
if(paginaSize && paginaActual) {
perfilQuery
.skip(paginaSize * (paginaActual - 1))
.limit(paginaSize)
}
perfilQuery.then(documentos => {
res.status(200).json({
posts: documentos
});
});
});
and in the form async/await
router.get('', async (req, res) => {
const paginaSize = +req.query.pagesize;
const paginaActual = +req.query.page;
const perfilQuery = Perfil.find();
try {
if(paginaSize && paginaActual) {
perfilQuery
.skip(paginaSize * (paginaActual - 1))
.limit(paginaSize)
}
await perfilQuery
res.status(200).json({
mensaje: "todos los perfiles",
perfil: perfiles
})
} catch (e) { res.status(500).send() }
})
but when making the request I get a status with error
500 , which could be my problem. I would appreciate it if you could help me.
The problem is that you are not actually executing your query when you use
async/await
.You have the following:
However,
perfilQuery
it is not an executable function or method on its own. It is an objectQuery
:Therefore, when you assign:
You are assigning a Query Object to the variable
perfilQuery
.The objects
Query
are not Promises , however they have a method.then()
to use them as if they were a Promise.Since you want to implement an asynchronous call
async/await
usingQuery
.The method
.exec()
executes the query and returns a Promise.According to the Mongoose documentation, this method takes a
String
or an as parametersFunción Callback
.The
String
represents the method to apply:'find'
,'update'
, etc. However, since the ObjectQuery
was instantiated using the static functionfind()
, it is not necessary to pass any value as a parameter:And since said query must return a list with the profiles found in the collection, we must assign its result to a variable:
So we already know the reason for the problem, but you hadn't found it, because you weren't debugging the error.
Calling the object directly
perfilQuery
like you were usingawait
was not causing the error. The error originated when trying to send an undefined variable:It is good practice in development to display error messages on the console:
That way you would have noticed the problem and maybe you would have found the solution yourself.
The complete code should look similar to the following:
I hope this clarifies your doubts and helps you solve the problem.