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.