首页 > 解决方案 > 如何同步调度一组 Vuex 动作(等待一组完成,然后调度另一个)

问题描述

我有几个返回 axios Promises 的 Vuex 操作。我想运行动作 X 几次,在这些动作结束后,我想运行动作 Y 几次,这是我尝试过的:

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)
}

在控制台的网络选项卡中,我希望看到发生成分操作调用,然后看到发生食谱操作。相反,我看到动作发生在所有地方,根本不是同步的。

如何在 recipes_actions 之前让所有的 ingredients_actions 发生?欢迎所有建议。

标签: javascriptasync-awaitvuex

解决方案


这是预期的吗?

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)
}

推荐阅读