Reputation: 1372
I'm trying to return the count from my database. The count().exec
method returns a Promise. I'm trying to resolve it in order to return the value to the user. But it returns undefined
.
It seems to me I have well used the async/await pattern, so what is wrong? I can't figure it out.
Here my snippet :
app.get("/blog/page/:pageTargeted", (req, res) => {
var countQuery = Posts.estimatedDocumentCount().exec();
// estimate count of document in collecion
function estimation() {
countQuery.then(count => {
countStringified = count.toString();
return countStringified;
})
} // console.log => successfully returns a value
// set Data
async function setData() {
let countStringified = await estimation();
return countStringified;
}
// send Data
function sendData() {
setData().then(result => console.log("result in sendData: ", result));
} // undefined
sendData();
});
*** Edit *** : it's now works, here's my new snippet:
setData().then(result => { // call an async/await functions chain
console.log("count in Post.find: ", result);
console.log("pageTargeted in Post.find: ", pageTargeted);
if (err) return console.error(err);
res.status(200).send(result);
});
I'm just wondering if I have to wrap all the ulterior process inside my function call. So maybe some refactoring will occur if possible to avoid some hell-type process. Anyway, meanwhile it works, so great, thanks.
Upvotes: 1
Views: 3073
Reputation: 156
Your estimation() function returns undefined instead of returning a promise, that is because you return the new string from the callback function.
replace countQuery.then(...)
with return countQuery.then(...)
.
Upvotes: 4