简体   繁体   中英

Firestore Return True or False instead of the Promise Object

So I have this function to store data in Firestore database but I wanted to check if the value exists already and based on that I want to return a boolean. I kept trying to solve this with async await but it did not seem to work. Finally when I added a return before performanceRef.get() , it solved the issue. Even though it solved the issue I'm not clear why. I know it must have something to do with async. Can someone please explain why adding that return solved the issue?

export const createUserPerformanceDocument = async (user, currentDate, answer ) => {

  const createdAt = currentDate.toLocaleDateString('en-US');
  const performanceRef = firestore.doc(`performance/${user}`);
  return performanceRef.get()
    .then(doc => {
      if(doc.exists) {
        const docData = doc.data();
        if (docData[createdAt]) {
          return false
        } else {
          try {
            performanceRef.set({ 
              [createdAt]: {
                Question: answer
              }
            },  { merge: true })
            return true
          } catch(error) {
            console.log('Error creating performance data!', error.message);
            return false
          }
        }
      } else {
        console.log("This user does not exist in the database");
      }
    })

}

It is not return what solved issue, probably there were some issues in your async/await code, and when you rewrote it into then callback it worked as expected.

Feel free to post your async/await version if you want more clear answer.

PS You don't use await keyword, so you don't need async modifier before function

Update from comments

Await keyword simply helps us stop function execution on current line and wait for promise to resolve. If you want to get result of the promise(it is named doc in your then callback) you need to store it in some constant:

const doc = await performanceRef.get()

So there you have it and can perform any kinds of validation like you do in then callback.

If you want to return validation result from this function, simply use return keyword like you already did.

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