-1

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?
Doug Allrich
  • 827
  • 1
  • 6
  • 18

1 Answers1

0

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)
        })
    })
  }) 
},
juanlumn
  • 6,155
  • 2
  • 30
  • 39
ßiansor Å. Ålmerol
  • 2,849
  • 3
  • 22
  • 24
  • I considered using `async/await` earlier but thought the second `await` would synchronously wait for the first `await` to resolve. Does the use of `new Promise` with `await` change that and allow the two awaits to be asynchronous instead? – Doug Allrich Nov 06 '19 at 14:58
  • I was able to test this code and it seems to also be synchronous at the `await` level, as far as I can tell. – Doug Allrich Nov 06 '19 at 22:12
  • @ßiansor Å. Ålmerol, would you be willing to take a look at another Vuexfire issue? https://stackoverflow.com/questions/59903702/how-to-use-moment-js-with-vuexfire – JS_is_awesome18 Jan 24 '20 at 21:39