[英]Waiting for async function to return true or false - how do I check return value?
I have an async function songAlreadyInQueue
that will return true if an ID is found in a database, false otherwise. 我有一个异步函数
songAlreadyInQueue
,如果在数据库中找到ID,则返回true,否则返回false。 I want to use the function like such: 我想使用这样的函数:
if(!songAlreadyInQueue(ref, id)){
// do stuff
}
But I know that since it's an async function, I have to wait for the result to come back before I truly know if it's true or false. 但我知道,因为它是一个异步函数,所以我必须等待结果回来才能真正知道它是真还是假。 What I have above is always false so I tried this:
我上面的内容总是假的所以我试过这个:
songAlreadyInQueue(ref, id).then((wasFound) => {
console.log("wasfound = " + wasFound)
if(!wasFound){
//do stuff
}
})
But that doesn't work either. 但这也不起作用。 What is the proper way to wait for this async function to finish?
等待此异步函数完成的正确方法是什么? This is what my async function looks like (simplified):
这是我的异步函数看起来像(简化):
async function songAlreadyInQueue(requestQueueRef, requestID) {
var querye = requestQueueRef.where("id", "==", requestID)
.get()
.then((snap) => {
snap.docs.forEach(doc => {
if (doc.exists) {
console.log("**************FOUND REQUEST IN QUEUE ALREADY!")
return true
}
})
return false
})
return querye // not sure if correct. Is this "returning a promise"?
}
With an async function you should use await instead of then()
so you're not creating another anonymous function. 使用异步函数,您应该使用await而不是
then()
这样您就不会创建另一个匿名函数。 You are returning from an anonymous function rather than the async function. 您将从匿名函数而不是异步函数返回。 try this.
尝试这个。
async function songAlreadyInQueue(requestQueueRef, requestID) { var snap = await requestQueueRef.where("id", "==", requestID).get() var found = false; snap.docs.forEach(doc => { if (doc.exists) { console.log("**************FOUND REQUEST IN QUEUE ALREADY!") found = true } }) return found }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.