首页 > 解决方案 > Await 不使用 firebase 批处理功能等待

问题描述

好吧,有一个简单的函数可以将加载程序的值设置为 true,并且在函数完成后将其设置为 false。但是有一个问题,我的 async/awaitasync/await函数的 await 不等待具有firebase batch writes. 我的代码:

const updateNegotiation = async title => {
  negotiationLoader.value = true
  await store.dispatch('actionUpdateNegotiation', {
  negotiation: listFromDialog.value, 
  title: title, 
  loader: negotiationLoader.value
  })
  negotiationLoader.value = false // the code doesnt await and put th loader's value to false
}

这是我的firebase功能batch writes

//vuex

async actionUpdateNegotiation({commit}, deal){
        const batch = db.batch()
        const reference = db.collection('negotiations')
        .doc(moduleUser.state.user.email)
        .collection('deals')

        const setRef = reference.doc(deal.title)
        .collection('clients')
        .doc(deal.negotiation.id)

        batch.set(setRef, deal.negotiation)
        batch.update(setRef, {
          ...deal.negotiation,
          status: deal.title
        })
        const deleteRef = reference.doc(deal.negotiation.status)
        .collection('clients')
        .doc(deal.negotiation.id)

        batch.delete(deleteRef)
        
         try{
          batch.commit()
          return {
            res: false
          }
        } catch (error) {
          console.log(error);
          return{
              error,
              res: true
          }
        }
      }

标签: javascriptfirebasevue.jsgoogle-cloud-firestoreasync-await

解决方案


关键字仅在await您调用的代码返回承诺时才起作用。您似乎所做的只是标记actionUpdateNegotiationasync,这还不够。

据我所知,内部唯一的异步操作actionUpdateNegotiation是对 的调用batch.commit(),因此您可以使函数返回一个承诺:

return batch.commit()

或者,您可以使用await

await batch.commit()

推荐阅读