Is there a possibility for the code following the await call to be executed in a random order if an async Vuex action is triggered twice?

const actions = {
  search: debounce(
    async ({ commit, dispatch, getters, rootGetters }, { page = 1 }) => {
      commit("setLoading", true);
      commit("setPage", page);

      console.log("Starting...")
      const randId = Math.random() * 100;
      console.log(randId);

      const results = await EventApi.get();

      console.log("Done: ", randId, `|${results.meta.slept}|`)

      // After `await`
      commit(page == 1 ? "setEvents" : "addEvents", results.events);
      // ... and a bunch more commits after that.

    }, 300, { leading: true, trailing: true })
  }
}

If the action above is called twice:

store.dispatch('search', { page: 1 });
store.dispatch('search', { page: 1 });

Let's assume the request made by the first call takes 10s to complete, and the request made by the second one takes only 1 second.

Is the code after await EventApi.get() in the second call executed after the one in the first call, even thought the request should have finished way earlier? I wouldn't have thought so but my experiment showed that it was the case, so something must be wrong with my code.

Here are the Vuex logs + some of my comments:

https://gist.github.com/niuage/9e2dcd509dc6d5246b3a16af56ccb3d3


In case it helps, here's the simplified EventApi module:

const get = async () => {
  const q = await fetch(someUrl);
  const result = await q.json();

  return result;
}

export default {
  get
}

I'm asking because I'm having an issue where, super rarely, I get my result count out of sync with the results actually displayed, so I was guessing that it could be because there was a race condition between multiple requests.

Answer №1

If we look at the scenario you provided, the second, shorter function call would execute first. This is because when using await, it only pauses within the scope of the async function.

When working with async/await, it essentially translates to two separate function calls that each return a promise. One call does not hinder the other in terms of execution time.

For demonstration purposes, consider the following example:

const delay = time => new Promise(resolve => setTimeout(() => resolve(), time))

async function wait(id, time) {
  await delay(time);
  console.log(id + ' complete.');
}

console.log('Starting 1...');
wait('#1', 5000);
console.log('Starting 2...');
wait('#2', 1000);
Refer to the bottom portion of the demo for the console output.

In the above demo, the async function can be re-written using .then like so:

function wait(id, time) {
  return delay(time).then(() => {
    console.log(id + ' complete.');
  });
}

To ensure that the second function call waits for the completion of the first one, both function calls should be within the context of an async function. For instance:

async created() {
  // Assuming the `search` action returns its http promise!
  await this.$store.dispatch('search', { page: 1 });
  await this.$store.dispatch('search', { page: 1 });
  ...
}

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

What is the method to turn off readonly property for input fields in Laravel?

I'm encountering an issue with my Laravel project. I have a form with an input field that has the readonly attribute set. <input type="text" name="anamFam" id="anamFam" value="{{$aFam->anam_cont}}" readonly> When I click the edit button, I ...

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...

What is the best way to delete an item from a React array state?

In my Firebase database, I have an array stored under the root branch called Rooms. Within the app, there is a state named rooms which is also an array. I successfully set it up so that when a user enters a new room name and submits it, it gets added to th ...

Tips for incorporating VueJS 2 global components within single file components

As I attempt to utilize a globally registered component (using Vue.component) within a single file component, I consistently encounter the following warning: vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the ...

Utilizing Angular to parse a JSON string generated with json.dumps

I am having trouble finding a solution that works for me. Currently, I am using python 3.6 (Django Rest Framework) on the server side and Angular 5 on the client side. This is the code on the server: class TypesView(APIView): def get(self,request): ...

Tips for streamlining the transfer of essential features from a main project to its duplicate projects

In my Angular project, I have a core repository on GitHub that serves as the foundation for custom client projects. Each time a new client comes onboard, we create a clone of the core project and make customizations based on their requirements. The issue ...

Learn the step-by-step process of dynamically adding elements to a JavaScript object in JSON structure

We are attempting to dynamically generate a JSON object using a for loop. The intended result should resemble the following: posJSON = [ { "position": [msg[0].Longitude, msg[0].Latitude], "radius": 0.05, "color": [255, 255, 0, ...

A guide to efficiently fetch JSON data synchronously using AngularJS

Trying to fetch data from a JSON file using AngularJS results in an error due to the asynchronous nature of the call. The code moves on to the next step before receiving the data, causing issues. The $http.get method was used. $http.get('job.json&apo ...

State calculation occurs too tardily

I'm working on creating a simple like button that changes color based on whether it's liked or not. I've tried to calculate this beforehand using React.useEffect, but it seems to be calculating afterwards instead... The hearts are initially ...

The Express application remains silent unless a port is specified for it to

Having recently started working with Node, I encountered an issue with Express. My application is only listening to localhost:PORT and I want it to also listen to just localhost. Here is the code snippet: ** var app = require('../app'); var debu ...

The conditional rendering logic in the ng-if directive does not seem to be synchronizing

Currently, I am delving into AngularJS and working on a basic application to gain familiarity with it. Within my app, there are four tabs: List, Create, Update, and Delete. However, my goal is to only display the Update and Delete tabs when I press the b ...

Tips for passing the name of a success function as a parameter in an AJAX request

My challenge is to create an AJAX call as a single function, where I pass the success function name as a parameter. Here's the function that I attempted: function MakeApiCall(dataText, apiName, functionName) { $.ajax({ url: apiUrl + apiName, ...

The type x cannot be assigned to the parameter '{ x: any; }'

Currently learning Angular and Typescript but encountering an error. It seems to be related to specifying the type, but I'm unsure of the exact issue. Still new at this, so any guidance is appreciated! src/app/shopping-list-new/shopping-edit/shopp ...

A guide on retrieving the values of all child elements within an HTML element using Puppeteer

I have been exploring the capabilities of puppeteer and am trying to extract the values from the column names of a table. <tbody> <tr class="GridHeader" align="center" style="background-color:Black;"> <td cl ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

What is the best way to extract value from a promise when combining it with async/await?

Looking to execute multiple async functions in parallel using async/await but unsure of how to retrieve the output from the async call. async function doit(){ const meta = call1; // async call 1 const data = call2; // async call 2 await meta; ...

The useState hook is failing to properly initialize with the provided props value

I am facing an issue with two components in my code. In the App component, I initialize a variable called chosenCount with zero and then set it to a different value (e.g., 56). However, when I click the set button, the Counter component is supposed to rece ...

"Utilizing the range option in a NodeJS request proves ineffective when attempting to stream HTML5

I have set up a nodejs request to serve videos with range support. The backend code looks like this: import { createReadStream, statSync } from 'fs'; const stats = statSync(path); const range = request.headers.range; const parts = ra ...

Preserve page configurations upon page refresh

I'm currently in the process of creating a 'user settings' form. Each list item represents a different section, such as Updating username, Updating email, and Changing password. It looks something like this: <li> <header>Ti ...