0๐
โ
// Raise isLoadign flag
this.$store.commit('isLoading', true);
// Initial data fetch
this.$store.dispatch('getAvailableProductGroups')
.then(() => {
// Call API for every available product
return Promise.all(this.$store.state.availableProductGroups.map(group => {
// Check if it's the last API call
return this.$store.dispatch('getProductsData', group);
});
})
.then((allResults) => {
this.$store.commit('isLoading', false);
});
But it SHOULD be in the store actions, not in vue-component.
0๐
You can create an array of promises with .map()
and resolve with .all()
Without async/await
this.$store.commit('isLoading', true);
this.$store.dispatch('getAvailableProductGroups').then(() => {
// Create an array of promises
const groupPromises = this.$store.state.availableProductGroups.map(group => this.$store.dispatch('getProductsData', group))
Promise.all(groupPromises).then( values => {
// array of promise results
console.log(values);
this.$store.commit('isLoading', false);
});
});
With async/await
async function doSomething() {
try {
this.$store.commit('isLoading', true);
await this.$store.dispatch('getAvailableProductGroups')
// Create an array of promises
const groupPromises = this.$store.state.availableProductGroups.map(group => this.$store.dispatch('getProductsData', group))
// Wait to resolve all promises
const arrayOfValues = await Promise.all(groupPromises);
this.$store.commit('isLoading', false);
} catch(err) {
console.log(err);
}
}
Source:stackexchange.com