[英]How do I fix this async/await function?
I am trying to get the number of documents in my mongodb collection using async and await.我正在尝试使用 async 和 await 获取 mongodb 集合中的文档数。 When I run this piece of code I get "TypeError: cb is not a function".
当我运行这段代码时,我得到“TypeError:cb 不是函数”。
I have tried using promises to get this to work, however I am still inexperienced with this topic and I am still learning how to work with promises.我已经尝试使用 Promise 来实现它,但是我对这个主题仍然缺乏经验,我仍在学习如何使用 Promise。
Here is the call这是电话
getFlashCard : function(colName, flashID, callback) {
var docCount = documentCount();
console.log(docCount);
}
Here is the function这是 function
async function documentCount() {
const count = await mongodb.collection("Interview Questions").count();
return count;
}
I am getting an error that says " cb(err, val) ^我收到一条错误消息,上面写着“ cb(err, val) ^
TypeError: cb is not a function at runInAsyncScope " TypeError: cb is not a function at runInAsyncScope"
Actually you dont need async
and await
for this because its already an promise.实际上,您不需要
async
并为此await
,因为它已经是 promise。 Just add an then
on the end:只需在末尾添加
then
:
mongodb.collection("Interview Questions").count().then(count => {
console.log("counted: " + count)
})
documentCount()
is an async
function. documentCount()
是一个async
function。 As such, it returns a promise.因此,它返回 promise。 All
async
functions return a promise.所有
async
函数都返回 promise。 So, the way you get a value out of a promise is the same as with any promise.因此,从 promise 中获取值的方式与任何 promise 相同。 You use
.then()
or await
on it.您使用
.then()
或await
它。 So, in getFlashCard()
, you could do something like this:因此,在
getFlashCard()
中,您可以执行以下操作:
getFlashCard : function(colName, flashID, callback) {
documentCount().then(docCount => {
console.log(docCount);
}).catch(err => {
console.error(err);
});
}
This assumes that you're using your mongodb.collection().count()
properly and that it returns a promise.这假设您正在正确使用
mongodb.collection().count()
并且它返回 promise。 If that's not the case, then you will also have to fix that (I don't personally know mongodb).如果不是这种情况,那么您还必须解决这个问题(我个人不知道 mongodb)。
FYI, it appears you created documentCount()
hoping to turn an asynchronous value into a synchronous value.仅供参考,您似乎创建了
documentCount()
希望将异步值转换为同步值。 You can't do that in Javascript.你不能在 Javascript 中这样做。 While
await
suspends execution within a function and lets you appear to write more synchronous looking code for asynchronous operations, it doesn't work across a function boundary.虽然
await
在 function 中暂停执行并让您看起来为异步操作编写更多同步的代码,但它在 function 边界上不起作用。 You cannot change an asynchronous value into a synchronous value in Javascript.您不能在 Javascript 中将异步值更改为同步值。 So, anyone who wants to use the
docCount
value will have to deal with it asynchronously as I've shown above in getFlashCard()
.因此,任何想要使用
docCount
值的人都必须像上面在getFlashCard()
中显示的那样异步处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.