使用then / catch异步获取VuexFire数据

给出以下名为init且可正常运行的vuex动作,该动作可获取settingsaccounts集合:

actions: {
  init: firestoreaction(({ bindFirestoreRef,commit },payload) => {
    bindFirestoreRef(
      'settings',fb.settings.doc(payload),)
      .then(() => commit('SETTINGS_READY',true))
      .catch((err) => {
        commit('snACKBAR_TEXT',err.message);
        Sentry.captureException(err);
      });

    bindFirestoreRef(
      'accounts',fb.accounts.where('program','==',payload),)
      .then(() => commit('accOUNTS_READY',err.message);
        Sentry.captureException(err);
      });
  }),},

我有两个问题:

  1. 代码似乎是同步运行的,但是我希望异步获取两个集合以最大化性能。如何实现?
  2. 是否可以重构此代码以使其更简洁,同时提供示例中提供的独立(和同步)then/catch功能?
zch05030148 回答:使用then / catch异步获取VuexFire数据

您可以使用async / await函数,然后在bindFirestoreRef构造函数中调用Promise

actions: {
init: firestoreAction(async ({ bindFirestoreRef,commit },payload) => {
    await Promise((resolve,reject) => {
      bindFirestoreRef('settings',fb.settings.doc(payload))
        .then((res) => {
          commit('SETTINGS_READY',true);
          resolve(res);
        })
        .catch((err) => {
          commit('SNACKBAR_TEXT',err.message)
          Sentry.captureException(err)
          reject(err)
        })
    })

    await new Promise((resolve,reject) => {
      bindFirestoreRef('accounts',fb.accounts.where('program','==',payload))
        .then((res) => {
          commit('ACCOUNTS_READY',err.message)
          Sentry.captureException(err)
          reject(err)
        })
    })
  }) 
},
本文链接:https://www.f2er.com/3155325.html

大家都在问