【问题标题】:Handling Async Await to use Firebase with react native处理 Async Await 以使用 Firebase 和 react native
【发布时间】:2021-04-01 10:36:41
【问题描述】:
const userID = firebase.auth().currentUser.uid

const checkRoomExists = async ()=>{
  var queryRef = firestore.collection("groups");
  try{
    console.log("userId: "+userID)
    var snapshot = await queryRef.where('participant', '==',userID).where('host','==',findParticipant).get()
    if (snapshot.empty) {
      console.log('No matching documents1.');
      return;
    }
    else{
      snapshot.forEach(doc => {
      setChatroomAlready(doc.id)
    })}
  }
  catch(e){
    console.log('Error getting documents', e);
  }
  finally{
    console.log("chatroomAlready :"+chatroomAlready)
  }
}

async function performCreateGroup () {
  console.log("1 :"+findParticipant)
  checkRoomExists();
  console.log("2 :"+chatroomAlready)
}
//first call 
1: ZUxSZP09fzRzndr7vhK8wr56j3J3
2: (blank)
//second call returns what I expected exactly
1: ZUxSZP09fzRzndr7vhK8wr56j3J3
2: zQN4hbgqjKhHHHc70hPn

这是我的代码,变量 chatroomAlready 返回 '' 但是,如果我使用 react-native 的功能快速刷新我的应用程序,它会很好地返回预期值 我认为这个问题的发生是因为我对 async-await 的了解较少。 有什么帮助或线索可以解决这个问题吗?

【问题讨论】:

  • 我不清楚是什么问题。 “在我快速刷新我的应用程序之前,我的变量 chatroomAlready 返回''”是什么意思?请编辑问题以更详细地解释什么不符合您的预期。
  • 我已经解决了我的问题,谢谢。
  • 查询时userID的值是多少?在您使用它之前记录它。我想你会对它的价值感到惊讶。请根据您的发现编辑问题。
  • 我已经测试过了,但 userId 的值只是我的预期。它返回了真正的 userId,尽管 chatroomAlready 什么也没返回。
  • 那么,您期望查询执行的操作与您期望的不同?我们看不到您数据库中的数据,因此我们不知道它应该做什么。

标签: javascript firebase react-native google-cloud-firestore async-await


【解决方案1】:

我宁愿使用以下语法:

queryRef.where('participant', '==',userID).where('host','==',findParticipant).get().then((snapshot)=>(
DO YOUR STUFF))

因为 queryRef 充当了一个承诺。

【讨论】:

  • queryRef 不“作为承诺”。它是一个查询类型的对象。代码使用 async/await 处理 get() 返回的承诺的方式没有任何问题。将其更改为使用then 不会影响结果。
猜你喜欢
  • 2019-01-05
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 2021-10-30
  • 2017-10-31
  • 2018-10-11
  • 2020-03-08
相关资源
最近更新 更多