Asynchronous VuexFire Data Fetch With Then/Catch

391 Views Asked by At

Given the following functioning vuex action named init that fetches a settings and an accounts collection:

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', true))
      .catch((err) => {
        commit('SNACKBAR_TEXT', err.message);
        Sentry.captureException(err);
      });
  }),
},

I have two questions:

  1. The code appears to run synchronously, but I want the two collections to be fetched asynchronously to maximize performance. How can that be achieved?
  2. Is it possible to refactor this code to be more concise and yet provide for the independent (and synchronous) then/catch functionality present in the example?
1

There are 1 best solutions below

3
On

You can use async / await function then call the bindFirestoreRef inside Promise constructor.

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', true);
          resolve(res);
        })
        .catch((err) => {
          commit('SNACKBAR_TEXT', err.message)
          Sentry.captureException(err)
          reject(err)
        })
    })
  }) 
},