[英]How to fix async function which returns `undefined`?
I'm trying to return the count from my database.我正在尝试从我的数据库中返回计数。 The
count().exec
method returns a Promise. count().exec
方法返回一个 Promise。 I'm trying to resolve it in order to return the value to the user.我正在尝试解决它以便将值返回给用户。 But it returns
undefined
.但它返回
undefined
。
It seems to me I have well used the async/await pattern, so what is wrong?在我看来我已经很好地使用了 async/await 模式,那么有什么问题呢? 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.
无论如何,同时它有效,太好了,谢谢。
Your estimation() function returns undefined instead of returning a promise, that is because you return the new string from the callback function.您的estimate() 函数返回undefined 而不是返回promise,这是因为您从回调函数返回了新字符串。
replace countQuery.then(...)
with return countQuery.then(...)
.用
return countQuery.then(...)
替换countQuery.then(...)
return countQuery.then(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.