【发布时间】:2019-03-12 07:59:28
【问题描述】:
我正在尝试从我的数据库中返回计数。 count().exec 方法返回一个 Promise。我正在尝试解决它以便将值返回给用户。但它返回undefined。
在我看来,我很好地使用了 async/await 模式,那么有什么问题吗?我想不通。
这里是我的 sn-p:
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();
});
*** 编辑 ***:它现在可以工作了,这是我的新 sn-p:
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);
});
我只是想知道是否必须将所有不可告人的过程包装在我的函数调用中。因此,如果可能的话,可能会进行一些重构以避免一些地狱式的过程。无论如何,它同时工作,太好了,谢谢。
【问题讨论】:
-
estimation()函数必须返回一个 Promise。 -
返回countStringified,同时感谢提示
-
不,它没有。您传递给
.then的回调 函数返回countStringified,但estimation()本身返回undefined。你可以简单地在.then()调用之前粘贴return。 -
哇,我编码了几个月,第一次发现“返回范围”问题。嗯,有趣
标签: javascript node.js async-await