[Vuejs]-Vuex – data from different modules are returned in random order when using then()

0👍

first of all, I need to correct myself, dispatch is an action, it is asynchronous, so you’re correct to use promises with them. (I’m used to mapping actions, so I don’t see them much)

anyway, the point of promises was to alleviate the “callback hell”. so if your structure is nested like this:

  • action
    • action
      • action
        • action

you’re defeating the point of using a promise in the first place.

Instead the point is to chain them in a readable fashion like so

  • action
  • action
  • action
  • action
actions: {
  loadRoamingHistory: function loadRoamingHistory(context, roamingFilter): Promise<Array<RoamingHistoryEvent>> {
    return store.dispatch('network/loadNetworks')
      .then(() => {
        return store.dispatch('country/loadCountries')
      })
      .then(() => {
        return providerApi.loadRoamingHistory(roamingFilter)
      })
      .then(data => { 
        // read already loaded networks and countries from store
        let networks = context.rootState.network.networks;
        let countries = context.rootState.country.countries;

        // .. some data processing using informations from 
        // networks and countries request, that are not allways available at this point..

        console.log('data processing');

        return commitSetRoamingHistoryEvents(context, data.roamingHistoryEvent);
      })
      .catch(err => console.log(err));
  }  
}

note that…
– the initial promise is not defined. Because the dispatch is asynchronous, it already creates a promise, we just add additional calls to it.
– when returning a promise inside a promise, the next then() will handle it, whether it is withing this function or outside of it
– your catch at the end will log an error anywhere along the chain of promises

Leave a comment