Troubleshooting Async Issue with Promises in JS/Vue

Greetings and thank you for taking the time to read my query.

Within my Vue component, named 'interactiveChart', there is a specific sequence of actions that occur when mounted:

  1. I begin by initializing various components such as the db manager and tool manager.

  2. I then proceed to call this.run(); in a specific order:

    • run() ->
    • (inside run) this.fetch->
    • then-> -logic goes here- || catch-> -handling error- ->
    • (inside run again) this.render(), which essentially renders the chart.
  3. Following these initial steps, I have event handlers set up within mounted that respond to specific events. After setting up these event listeners, I call this.render() again because some events may alter chart options. However, the challenge arises when different events require data for multiple ids, not just one. To address this, I use an array called idNotations to store all the ids needed for data parsing and employ a for of loop within this.run() to fetch data for each id. The issue I'm encountering is:

the function this.render() inside this.run() gets executed multiple times if multiple ids are given, resulting in the chart reloading repeatedly momentarily before displaying correctly. The data itself is displayed accurately, but the chart reloads before all data for each id is fetched. The desired outcome is to execute render() only once, after all promises have been fulfilled. Moving render() outside the for of loop doesn't work because run() is not asynchronous. How can this issue be resolved?

  mounted() {
console.log('Function Call: mounted()');

//Initialization
this.selectedTimeSpan = timeSpansArray.find((el) => el.timeSpan == '5Y');
this.mdg2Client = globalMdg2ClientFactory.createMdg2Client();
this.highchartOptions = this.getHighchartsOptions();
this.run();

/**
 * Events Below
 */

//When Timespan Changes
this.$root.$on('chartZoom', (payload) => {
  console.log('[Event Emitted] - Timespan Changed');
  this.interactiveChart.showLoading('Loading Data..');
  this.selectedTimeSpan = timeSpansArray.find(
    (el) => el.timeSpan === payload.timeSpan
  );
  this.run();
});

//When Chart Type Changes
this.$root.$on('chart-type', (payload) => {
  console.log('[Event Emitted] - Chart Type/Data Changed', payload);
...

Answer №1

This issue was resolved thanks to utilizing Promise.all(), following a recommendation from the recoilnetworks user. Grateful for their help!

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

Instead of using `await asyncCall()`, try using `(await asyncCall())[0]`

After examining the Typescript code below, I'm curious to understand the rationale behind assigning myArray with (await asyncRPCCall())[0] instead of simply using await asyncRPCCall(). Why is the result placed inside () and why return only the first e ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

Attempting to spread a non-iterable instance is invalid. For non-array objects to be iterable, they must have a [Symbol.iterator]() method

data(){ return { tables:[] } }, mounted(){ this.fetchData() }, methods:{ fetchData(){ var subscription = web3.eth.subscribe('logs', { address: '0x123456..', topics: ['0x12345. ...

Add a variety of input values to a div in designated spots

Objective: The aim is to allow the user to connect form fields with specific locations within a content from another div, and then add the text entered in individual input fields to those corresponding locations. Here is the link to the fiddle HTML: < ...

How can I create a mipmap for a planet using three.js?

Recently, I delved into the realm of mipmapping and its definition, but I find myself uncertain about how to effectively implement this technique in three.js. After exploring a couple of examples like: and also this one: Both examples appear to utilize ...

The JavaScript function is returning a value of undefined

I encountered an issue where my Javascript function is returning undefined even though it alerts the correct value within the function itself. I have a setup where I call the function in my 1st controller like this: CustomerService.setName(data.name); A ...

Turn off logging functionality in a Node.JS environment

I am looking to turn off logging for specific environments in my Node.JS application using Express. Would the following method be considered the most optimal way to disable logging within Node.JS applications? if(process.env.NODE_ENV == "production") { ...

Animate out Material UI element with zoom effect and then remove it from the

I'm currently working on a dynamic user interface that allows for adding and removing items dynamically. Each item has both an add and remove button, with a special animation effect using Zoom. While this works smoothly when adding new items, I encoun ...

Enhancing the Google canvas script to incorporate numerous markers

Currently, I am using a template that includes a Google map with coordinates set in JavaScript. The code for the marker on the map is as follows: //Google Map var latlng = new google.maps.LatLng(44.761128,21.227395); var settings = { ...

Showcasing pictures on ReactJS

I am currently working on developing an application to showcase images on my React webpage. These images have already been uploaded to a local folder. In order to integrate my React application with a NodeJS server and MongoDB, I connected the two. My goa ...

Asynchronous function that delivers results from factory after processing

I am facing an issue with a service(factory) that relies on another service to fetch data. Here is a simplified version of the code: factory('myFactory', function(anotherFactory) { var factoryObject = {}; factoryObject.myMethod = () ...

Guide on inserting text within a Toggle Switch Component using React

Is there a way to insert text inside a Switch component in ReactJS? Specifically, I'm looking to add the text EN and PT within the Switch Component. I opted not to use any libraries for this. Instead, I crafted the component solely using CSS to achie ...

Verifying if every item in an array exists within multiple arrays

I am struggling to find a solution to this problem. Imagine there are 6 sets of colors with varying amounts of colors in each, and colors may be repeated: ['white', 'blue'] ['green', 'yellow'] ['black'] [ ...

disable event listeners on the DOM

I am currently developing a web framework and focusing on integrating XSS prevention measures. I have successfully implemented data escaping for database storage, but now I am faced with the challenge of allowing users to save generated HTML without riskin ...

Should I opt for using mounted or created?

While working with VUE, I encountered an issue where I needed to pass an ID from a parent component to a child component. However, I noticed that when the child component is called again through a button after the initial render, the ID becomes null. Shoul ...

Error: Required variable missing in AJAX Post request

When making an ajax call, I use the following code: o.open("POST",q,true); o.setRequestHeader("Content-type","application/x-www-form-urlencoded"); o.setRequestHeader("Content-length",p.length); o.setRequestHeader("Connection","close"); Here, q represent ...

Delay the axios get request in the useEffect

Working with React JS, I have implemented a useEffect hook to request data from a database via an Express server when the page renders. However, if the server is down, the app will continue to make thousands of requests until it crashes. Is there a way to ...

Utilize the $sample operator following the $group stage in MongoDB queries

Consider the dataset provided below: {company:"One", employee:"John"}, {company:"One", employee:"Mike"}, {company:"One", employee:"Donald"}, {company:"One", employee:"Mickey"}, {company:"Two", employee:"Johnny"}, {company:"Two", employee:"Da ...

How can I fix the position of the close button when using the paper component of a modal in material ui to ensure responsiveness on the screen

I recently created a cards page where multiple cards are displayed. Each card opens a modal component when clicked, but unfortunately, the close button is not functioning properly. Here's an image showing the issue with the button's position whe ...

``There appears to be an issue with the functionality of the jQuery

I've been experimenting with using AJAX in a PHP form, but for some reason it's not working as expected. I'm at a loss trying to figure out why. Here is my code: <!DOCTYPE html> <html lang="es"> <head> <title>< ...