简体   繁体   中英

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. 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. 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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM