Firebase Firestore:离线写入操作的承诺何时解决?

Firebase Firestore: when do promises from offline write operations resolve?

我按照文档中的说明激活了离线功能,例如:

firebase
    .firestore()
    .enablePersistence()
    .then(() => {
      console.log('offlinemode acctivated')
    })

日志如我所料出现。

像这样添加数据时:

db
    .collection('foo')
    .add({foo: 'bar'})
    .then(docRef => {
      console.log('Added Foo: ', docRef.id)
      // do some stuff here with the newly created foo and it's id.
    })
    .catch(console.error)

离线时 .then().catch() 都没有接到电话。即使在执行此回调时将对象添加到我的离线数据库中的 foo 集合中也是如此:

db
    .collection('foo')
    .onSnapshot(callback)

我错过了什么吗?我希望承诺要么失败要么解决,所以我可以做出相应的反应。

只有当服务器确认写入已完成时,Firestore 中写入操作的承诺才会解决,即使它们可能已成功写入本地缓存。

这是我的解决方案:

  1. 我将调用包装在一个函数中,该函数最终应该 return 一个解决承诺,无论 offline/online 状态如何
  2. 然后我从 onSnapshot 获取保存的文档,其中 return 将文档写入本地缓存(在线和离线工作)。

这是我的代码(带有一些打字稿):

export function dbWritePromise(functionPromise: Promise<any>): Promise<any>{
  if(window.navigator.onLine){
    return functionPromise
  }
  else{
    return Promise.resolve()
  }
}

// I grabbed this function from a Github issue one upon a time
export function docSnapshotPromise(ref: firebase.firestore.DocumentReference): Promise<any>{
  return new Promise((resolve, reject) => {
    const unsubscribe = ref.onSnapshot(doc => {
      resolve(doc)
      unsubscribe()
    }, err => {
      reject(err)
      unsubscribe()
    })
  })
}

正在使用(我在这里使用 update 函数,但 add 的工作方式相同)此代码正在处理来自名为 organizations 的集合中的文档:

try{
  //update org doc
  await dbWritePromise(orgRef.update({
    name: 'New and improved name here'
  }))
  // wait for this updated doc to be written to local cache, then we can get the updated org
  const updatedOrgRef = await docSnapshotPromise(orgRef)
  const updatedOrg = updatedOrgRef.data()
  console.log(updatedOrg.name) // outputs the new and improved name
}
catch (err) { handleError(err) }

抛出的错误可能是本地缓存的一些错误,也可能是服务器错误,例如 Firestore 规则(在线时)return导致的权限错误。显然,离线模式下服务器的任何错误都会默默地失败,即使应用程序重新在线。

我很乐意在这里看到其他人的解决方案!