Guide on calling a series of Vuex actions in synchronous order (ensure completion of one set before dispatching the next)

I have a situation where I need to execute multiple Vuex actions that return axios Promises. Specifically, I want to run action X several times and then follow it up with action Y several times. Here's my current approach:

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

When checking the network tab in the console, I expect to see the ingredients_actions calls being made first, followed by the recipes_actions. However, the actions seem to be executed out of order and not synchronously as intended.

I'm looking for suggestions on how to ensure all the ingredients_actions are completed before the recipes_actions start running. Any advice or tips would be greatly appreciated.

Answer №1

Is this the expected behavior?

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

Answer №2

It is crucial to wrap your map within Promise.all() immediately, as the iteration functions are uncontrolled (errors will not be handled). Alternatively, you can consider using <Function>.bind().

Consider trying the following approach:

async save() {
  const ingredients = [{ 1 }, { 2 }];
  const recipes = [{ a }, { b }, { c }]

  await Promise.all(ingredients.map(ingredient => this.$store.dispatch('saveIngredients', ingredient)));
  await Promise.all(recipes.map(recipe => this.$store.dispatch('saveRecipe', recipe)));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve information and functions from one component in a separate component

I currently have two components: ContainerSidebar.vue <!-- Sidebar --> <div id="b-sidebar"> <div class="change-image"> <img :src="profile.avatar != null ? profile.avatar+'#&apo ...

Creating a simulated RESTful backend using Sinon.js for an Angular.js project

In the process of developing my Angular.js application, I am incorporating RESTful services that utilize the $resource service. While this app will eventually connect to a Java Spring application, I am currently focusing on creating an isolated mock server ...

Struggling to interpret JSON data from an AJAX call using jQuery in a Python/Flask application

Currently, I am attempting to analyze a POST request sent via AJAX using jQuery in a python script. The structure of the request is as follows: request.js function get_form_data($form){ var unindexed_array = $form.serializeArray(); var indexed_ar ...

Align audio and video elements in HTML5 using JavaScript

I am facing a situation where I have two files - one is a video file without volume and the other is an audio file. I am trying to play both of these files using <audio> and <video> tags. My goal is to make sure that both files are ready to pla ...

Compress PDF documents directly from a given web address

I'm currently attempting to create a zip file containing multiple PDF files by using the archiver npm module. While I have successfully managed to zip files from local memory to my machine, I am facing difficulties when trying to use URLs in the fs.cr ...

Instructions on accessing environment variables within a Grunt configuration file

My Angular application operates in three different environments: Development, Staging, and Production. When Heroku builds the application based on my build script, a Gruntfile includes a release task that uglifies the code. Heroku executes the command Gr ...

Easiest way to retrieve data with Backbone.js collections

I am currently attempting to download, parse, and display a list from the XML data received from my server using Backbone.js. Below is the code snippet: var Item = Backbone.collection.extend({ url: "http://myurl.com/file.xml", parse: function() { ...

"Exploring the power of Ajax in handling JSON arrays

Using JSON data format with jQuery might just be the solution I need, if only it actually worked. Within my remoteServiceEngine.php file, I have a snippet that looks like this: $jResponse[0] = json_encode(array("jAction" => "add", "jObject" => "lis ...

What could be causing the issue with my dynamic sitemap.xml file not functioning properly?

I have encountered an issue with creating a dynamic sitemap in my Next.js app. Despite following the instructions in the Next.js documentation and placing a sitemap.js file inside my app directory, I am seeing a 404 error when trying to access http://local ...

Feature to insert a fresh row into SAPUI5 table

I've been attempting to insert new rows into a SAPUI5 table with the click of a button. Despite watching numerous tutorials online, I haven't found one that fits my specific situation. Currently, the JSON data is loaded via a mock server with th ...

The hyperlink is unclickable because of the menu

The code below contains a menu on the right side with a hover effect and some content with a link. However, the link is not clickable due to the menu. .menubar{position: fixed;right:0;top: 50%;transform: translateY(-50%);-webkit-transform: translateY(-5 ...

Understanding the mechanics of utilizing node modules and requiring them within an Express 4 router

After initiating a node project using an express 4 generator, I have set up the following routing code in the /routes/index.js file: // ./routes/index.js var express = require('express'); var router = express.Router(); router.get('/' ...

Tips for effectively engaging with a Component's aggregationUnleash the full potential of

After configuring an aggregation for my Component, here is what it looks like: aggregations : { busyDialog : { type: "sap.m.BusyDialog", multiple: false } } The aggregation is named ...

Is it possible to utilize the 'in' operator to locate the term 'length' in... Is there a need to modify the string?

I have been looking through the existing questions but haven't found a solution that completely explains how to resolve my issue. As someone new to JSON, I'm still trying to grasp all of its concepts. My goal is to create a dynamic table where us ...

Discovering whether an image contains a caption with the help of JavaScript

There are various websites that display captions on images in paragraphs, h1 tags, or contained within a div along with the image. I am interested in learning how to determine if an image has an associated caption using JavaScript, especially when the cap ...

involving a variable in css styles using javascript

Is it possible to set a margin-left using a variable in JavaScript? If so, how can this be accomplished? The margin left should be equivalent to the clientWidth of the text: let hoverBubble = document.getElementById(id); let linkWidth = link.clientWidth ...

I need help figuring out how to handle click events when using VueJS 2.0 in conjunction with a vue-mdl menu component

While @click doesn't seem to respond, v-bind:click does register. However, I'm facing the challenge of not being able to access the mdl-menu or mdl-menu-item components in order to add the method. The goal is to implement something like @click=" ...

Three.js - Display a model with material that can be visible without the need for a light source

I am currently utilizing Three.js, specifically version 71. My workflow involves creating models in Blender, exporting them as JSON files, and then using THREE.JSONLoader to incorporate these models into my scene as shown below: this.jsonLoader.load(path ...

Dynamically load select options using Ajax

I'm a newcomer to javascript and ajax, and I'm working on implementing Ajax to display the current category on my HTML select in a CodeIgniter project. Below is the code snippet: HTML: <select class="form-control" name="category" id="categor ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...