Running a function in Vue.js after another function, synchronously

I want to ensure that one function runs after another in VueJs

data: function() {
        return {
            stuff: '',
            myArray:[
                {
                    "id": 0,
                    "value1": 0,
                    "value2": '',
                    "etc": ''
                },
            ],
        };
},
methods: {
     fetchData() {
            axios.get('/api/get-data')
                .then(res => {
                    this.myArray = res.data;
                }).catch(err => {
                console.log(err)
            })
        },
     runThisAfterArrayPopulates(){
        /*a bunch of code that depends on the contents from this.myArray , so it is crucial that this.myArray is completely populated/finalized */
       for (i = 0; i < this.myArray.length; i++) {
                /*during development, this.myArray.length is 60 on the server, but on production, it is only 1 */
                }
            }
     }
}

The sequence of running these functions is currently:

created: function () {
        this.fetchData();
},
mounted: function () {
        document.onreadystatechange = () => {
          if (document.readyState == "complete") {
            console.log('Page completed with images and files ensuring execution at the very end')
            this.runThisAfterArrayPopulates();
          }
        }
},

While testing locally, everything works fine as expected.

However, once deployed to production, the function this.runThisAfterArrayPopulates(); executes when this.myArray contains only one object and not the complete axios data. It seems like there isn't enough time for it to fully populate. I suspect this is due to the longer process of fetching data from axios on the production server compared to localhost, causing the function runThisAfterArrayPopulates() to execute before the array is fully loaded due to JavaScript's asynchronous nature.

I have read about promises, but I'm unsure how to apply them here.

I tried calling this.fetchData(); within beforeMounted instead of created:, and also attempted to place this.runThisAfterArrayPopulates() inside the axios .then(), but I still face an issue with an array length of 1 in production.

Note: The code functions perfectly in development, and clicking a button with the following code also behaves correctly:

<button @click="runThisAfterArrayPopulates()">Click me</button>

This confirms that the problem lies in the order of execution.

Answer №1

Make the necessary changes in your code like this.

    methods: {
         fetchData() {
                
                axios.get('/api/get-data')
                    .then(res => {
                        this.myArray = res.data;
                        this.runThisAfterArrayPopulates(); // Ensure to call this method after array is populated.
                    }).catch(err => {
                    console.log(err)
                })
            },
         runThisAfterArrayPopulates(){
            /*a lot of code that depends on the data from this.myArray , so it must be fully populated/finalized */
         }
    },


created: function () {
        // this.fetchData();
},
mounted: function () {
        this.fetchData();
},

This should not be an issue since the handler method is an arrow function. However, if you decide to use a regular function instead of an arrow function, be mindful of this potential pitfall.

UPDATE: Consider moving the call to this.fetchData(); within the mounted hook itself.

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

The challenge of vertically aligning text in a dynamically generated div

Currently, I am in the process of developing a straightforward application that allows for the dynamic addition of students and teachers. I am dynamically adding divs with a click function. To these dynamically created divs, I have assigned the class "us ...

What could be the reason for TypeScript being unable to recognize my function?

In my code, I have a Listener set up within an onInit method: google.maps.event.addListener(this.map, 'click', function(event) { console.log(event.latLng); var lt = event.latLng.lat; var ln = event.latLng.lng; co ...

Trouble with jQuery click event on dynamically generated elements

I have a jQuery function that iterates through each element inside a specified div (#container) and triggers a JavaScript alert whenever a span is clicked. Everything functions correctly when the spans are static. However, when I include code like this: ...

How to create a freeze panes feature like MS Excel using HTML and CSS

In my web application for iPad using Angular JS, HTML5, and CSS3, I'm facing a challenge with a large table that requires both horizontal and vertical scrolling, along with a "freeze-pane" feature similar to MS Excel. Currently, I've divided the ...

assign a role to a discord.js user using the role stored in the client class variable

Is there a way to dynamically assign a role to a user using the client variable const client = new Client({ intents: [GatewayIntentBits.Guilds] }); instead of through an interaction? The user's role needs to be updated when a 3rd party request is rec ...

Ways to update the cart page automatically after quantity changes in Shopify

I have made some updates to the Approach and now I am using JavaScript. I've also updated the script and its logic, which is pasted below. Please take a look and see if you can assist me. I am trying to display information on the top of the cart page ...

Choose up to three elements using jQuery

DEMO I'm currently working on a project where I need to select only 3 items at a time. However, all the elements are being selected instead. Can someone please provide guidance on how to achieve this? "If a user wants to select another element, th ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...

The Ajax GIF Loader is not functioning in the latest versions of Internet Explorer and Firefox, but it is running smoothly in

The animated GIF loader functions correctly in the latest version of Chrome, but does not animate when viewed in IE and Firefox. Below is the code snippet: $("#DIALOG").dialog({ buttons : { "Yes" : function() { ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

Angular: refresh page post redirection

I am working on a function that redirects to another page, and I am looking to have the redirected page reload once the redirection is complete. I specifically need the login page to reload after being redirected to it. The usual 'window.location.rel ...

When working with TextareaAutosize component in MUI, an issue surfaces where you need to click on the textarea again after entering each character

One issue that arises when using TextareaAutosize from MUI is the need to click on the textarea again after entering each character. This problem specifically occurs when utilizing StyledTextarea = styled(TextareaAutosize) The initial code snippet accompl ...

Tips on how to showcase various information in distinct tabs using VueJS

I am currently working on a website project utilizing the VueJS framework and Vuetify template. My goal is to showcase different content under separate tabs, however, I'm encountering an issue where the same content is being displayed in all three tab ...

AngularJS promise fails to resolve when attempting to read a file using the FileReader

Can someone assist me with a function I am trying to create in my service? I want the function to use FileReader to read a small image file and return the result in a promise to my controller. The issue is that while the file reaches the service without an ...

Unable to invoke a function in JavaScript

When I try to create a user in the database by calling the function createOne inside createProfile, it seems like the function is not getting executed. Even though the route is functioning properly, I'm facing an issue with calling a function within a ...

Error in Mongoose validation: "Please provide a value for the 'first' field and the 'last' field."

Another user has previously posted a similar question, but I'm still struggling with my MongoDB website. I am working on a project to store names using mongoose. Here is the code for my routes and models: const router = require("express").Router(); c ...

Exploring the Concept of Callbacks in JavaScript

What happens behind the scenes when a function is passed as a parameter in JavaScript and how does the engine recognize it as a callback? ...

Using jQuery to slide in dynamically generated content

I am in the process of developing a straightforward content slider that has the capability to manage dynamically added content. Unfortunately, none of the supposedly "lightweight" plugins I came across offered this functionality or, if they did, it was not ...

What is the best way to keep the navbar contained within the parent div (hero image) no matter the size of the screen?

After working on adjusting my website layout for different screen sizes, I encountered an issue with the navbar overflowing the parent image when viewed on my laptop. Despite trying both relative and absolute positioning for the .navbar element and setting ...

Updating Vue state when the browser's back button is clicked

I'm currently working on a login page that features various provider options. When a user clicks on a provider, they are directed to the sign-in page of that specific provider. Within this login component, there is a boolean variable called "pageRedir ...