Search code examples
javascriptasync-awaitvuex

How to dispatch a set of Vuex actions synchronously (wait for a set to settle, and then dispatch another)


I have a couple of Vuex actions that return axios Promises. I want to run action X a few times, and after those actions end, I want to run action Y a few times, here's what I've tried:

async save() {
  const ingredients = [{ 1 }, { 2 }]
  const ingredients_actions = ingredients.map(async ing => await this.$store.dispatch('saveIngredients', ing))
  const recipes = [{ a }, { b }, { c }]
  const recipes_actions = recipes.map(async recipe => await this.$store.dispatch('saveRecipe', recipe)

  await Promise.all(ingredients_actions)
  await Promise.all(recipes_actions)
}

In the network tab in the console I expect to see the ingredients_actions calls happen, and then see the recipes_actions happen. Instead I'm seeing the actions happen all over the place, not synchronously at all.

How to make all the ingredients_actions happen before the recipes_actions? All suggestions welcome.


Solution

  • Is it what is expected ?

    async save() {
      const ingredients = [{ 1 }, { 2 }]
      const ingredients_actions = ingredients.map(async ing => await this.$store.dispatch('saveIngredients', ing))
      await Promise.all(ingredients_actions)
    
      const recipes = [{ a }, { b }, { c }]
      const recipes_actions = recipes.map(async recipe => await this.$store.dispatch('saveRecipe', recipe)
      await Promise.all(recipes_actions)
    }