简体   繁体   English

Firestore 返回 True 或 False 而不是 Promise Object

[英]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.所以我有这个 function 将数据存储在 Firestore 数据库中,但我想检查该值是否已经存在,并基于此我想返回一个 boolean。 I kept trying to solve this with async await but it did not seem to work.我一直试图用 async await 解决这个问题,但它似乎没有用。 Finally when I added a return before performanceRef.get() , it solved the issue.最后,当我在performanceRef.get()之前添加一个return时,它解决了这个问题。 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.它没有return解决的问题,可能在您的 async/await 代码中存在一些问题,当您将其重写为 then 回调时,它按预期工作。

Feel free to post your async/await version if you want more clear answer.如果您想要更明确的答案,请随时发布您的 async/await 版本。

PS You don't use await keyword, so you don't need async modifier before function PS你不使用await关键字,所以function之前不需要async修饰符

Update from comments从评论更新

Await keyword simply helps us stop function execution on current line and wait for promise to resolve. Await 关键字只是帮助我们停止 function 在当前行执行并等待 promise 解决。 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:如果您想获得承诺的结果(在您的 then 回调中被命名为 doc),您需要将其存储在某个常量中:

const doc = await performanceRef.get()

So there you have it and can perform any kinds of validation like you do in then callback.所以你有了它,并且可以像在 then 回调中那样执行任何类型的验证。

If you want to return validation result from this function, simply use return keyword like you already did.如果你想从这个 function 返回验证结果,只需像你已经做的那样使用 return 关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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