【问题标题】:How to make sure all data is written into Firestore in a sequential order?如何确保所有数据按顺序写入 Firestore?
【发布时间】:2020-10-11 11:16:04
【问题描述】:

我正在尝试创建一个用户个人资料,说明该个人资料来自我应用中的一位企业主。它应该创建配置文件,然后将“roles”数组与“businessOwner”等信息合并,并添加“businessId”。

有时,代码会无缝运行。在其他时候,只会将角色和业务 ID 传递给创建的用户(所有其他信息都不会!)。

  async function writeToFirebase(values) {
    authService.createUserWithEmailAndPassword(values.user.email, values.user.senha).then(
      async function (user) {
        userService.createUserProfileDocument(values.user)
        const uid = user.user.uid
        const userRef = await userService.doc(uid)
        console.log('userRef', userRef)
        try {
          values.user.uid = uid
          const { id } = await businessPendingApprovalService.collection().add(values)
          await userRef.set({ roles: ['businessOwner'], businessId: id }, { merge: true }) 
        } catch (error) {
          console.error('error merging info')
        }
      },
      function (error) {
        var errorCode = error.code
        var errorMessage = error.message
        console.log(errorCode, errorMessage)
      },
    )
  }

这是 createUserWithEmailAndPassword:

async createUserProfileDocument(user, additionalData) {
    if (!user) return
    const userRef = this.firestore.doc(`users/${user.uid}`)
    const snapshot = await userRef.get()
    if (!snapshot.exists) {
      const { displayName, email, photoURL, providerData } = user
      try {
        await userRef.set({
          displayName,
          email,
          photoURL, 
          ...additionalData,
          providerData: providerData[0].providerId,
        })
      } catch (error) {
        console.error('error creating user: ', error)
      }
    }
    return this.getUserDocument(user.uid)
  }

【问题讨论】:

  • 我认为问题出在这条线上const snapshot = await userRef.get()。您必须使用then() 以确保您在承诺返回后获得spanshot。请查看此doc,了解如何获取文档。
  • 所以我可以完全摆脱 createUserProfileDocument 函数中的异步等待?
  • 我的评论是要指出,为了解决承诺权,您需要使用then() 以确保在承诺返回后获取快照。

标签: javascript reactjs google-cloud-firestore


【解决方案1】:

我认为问题出在这条线上const snapshot = await userRef.get()

documentation 中所述,您应该使用then() 函数获取快照,以便首先返回承诺。

【讨论】:

    【解决方案2】:

    我认为您还需要等待以下内容:-

    await userService.createUserProfileDocument(values.user)
    

    由于您在此处设置用户信息(等待 userRef.set),如果您不等待承诺,那么有时,您的下一个代码块(等待 userRef.set({角色: ['businessOwner'],) 执行,然后您的承诺可能会得到解决。因此,有时您可能无法获得其他信息。

    你还需要处理createUserProfileDocument的错误情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2010-09-27
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      相关资源
      最近更新 更多