【问题标题】:Firebase Firestore: when do promises from offline write operations resolve?Firebase Firestore:离线写入操作的承诺何时解决?
【发布时间】:2018-04-13 13:22:49
【问题描述】:

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

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)

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

【问题讨论】:

    标签: javascript firebase google-cloud-firestore offline


    【解决方案1】:

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

    【讨论】:

    • 好的,我明白了。我如何获得使用 .add() 创建的对象的 ID?
    • 这听起来像是一个不同的问题,可以单独提出。
    • 你是对的。抱歉不够具体:stackoverflow.com/questions/49829714/…
    【解决方案2】:

    这是我的解决方案:

    1. 我将调用包装在一个函数中,无论离线/在线状态如何,该函数最终都应返回解析承诺
    2. 然后我从onSnapshot 获取保存的文档,它返回写入本地缓存的文档(在线和离线均可)。

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

    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 规则返回的权限错误(在线时)。显然,在离线模式下服务器的任何错误都会静默失败,即使应用程序重新上线。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2013-06-22
      • 2019-12-20
      • 2018-06-26
      相关资源
      最近更新 更多