What is preventing me from retrieving my JavaScript array by index outside of the d3 then function?

My main objective is to construct a d3 stacked diverging bar chart. The issue I'm facing is that even though the votesData array is successfully created from the data, I can only access this data within the d3 then function where it's generated.

Sample Code:

var votesData = [];

//fetching data from votes route
d3.json("/votes").then(function (data) {
    
    //iterating through objects in the route
    data.forEach(function (d) {

        //converting data to numeric values
        demYes = +d.democratic.yes
        demNo = ~d.democratic.no 
        repYes = +d.republican.yes
        repNo = ~d.republican.no
        indYes = +d.independent.yes
        indNo = ~d.independent.no

        //appending necessary data to votesData array
        votesData.push( 
            {"name": d.bill.bill_id,
            "question": d.question,
            "description": d.description,
            "votes": [
                {"category": "Democratic Yes",
                 "value": demYes },
                {"category": "Democratic No",
                 "value": demNo},
                {"category": "Republican Yes",
                 "value": repYes},
                {"category": "Repulican No",
                 "value": repNo},
                {"category": "Independent Yes",
                 "value": indYes},
                {"category": "Independent No",
                 "value": indNo}
            ]
        })
    });
    console.log(votesData);
    console.log(votesData[0]);


});
console.log(votesData);
console.log(votesData[0]);

The initial log outputs return the expected array and first object, however, when attempting to access the object outside the d3 then function, the second logs display the votesData object but trying to retrieve the first index results in "undefined". Why is this happening? Is there a way to loop through this object outside of the d3 then function? Or is it recommended to include everything needed within the svg area inside that function?

Answer №1

The logic inside the then block is asynchronous. This means it is scheduled to be executed when the thread has available time, and the promise to read a /votes file has been resolved. Therefore, the code executes in the following order:

var votesData = [];
console.log(votesData);
console.log(votesData[0]);

//access votes route
d3.json("/votes").then(function (data) {
    ...
});

This is why it returns undefined initially – it has not yet been executed! To work around this issue, it is common practice to move all your logic inside the .then() block or utilize ES2017's async/await.

var votesData = [];

//access votes route
const data = await d3.json("/votes");

//loop through objects in route
data.forEach(function (d) {

    //convert data to numeric
    demYes = +d.democratic.yes
    ...
}

console.log(votesData);
console.log(votesData[0]);

Ultimately, using async/await compiles to the same result as utilizing the .then() solution, providing an easier coding experience.

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 for transmitting a concealed attribute "dragable" to my component?

Currently, I have successfully integrated a here map into my project, but I am now tackling the challenge of adding draggable markers to this map. To achieve this, I am utilizing a custom package/module developed by my company. This package is designed to ...

Exporting data from CSV files with PHP

I have a MySQL table with the following data: INSERT INTO `camp_expense` (`expense_id`, `camp_regtype`, `camp_name`, `camp_date`, `expense_name`, `expense_amount`, `expense_total`, `calculation_date`, `expense_status`) VALUES (1, 'Fre ...

What could be causing the repetition of the same cookie in my request header when using jQuery ajax?

Stuck in a dilemma for hours now, seeking assistance or suggestions from anyone who can help me out. To sum it up, I have an asp.net web api application where I am trying to fetch data from a web api and populate multiple dropdown lists on a page using jQ ...

Why is it that when I store a DOM element reference in a JavaScript Array, I cannot reuse that stored reference to add an event listener

I have a little confusion and I hope someone can help me out. I am facing an issue with dynamically created buttons, where each button has a unique id. To keep track of these buttons in a well-organized manner, I store their references using a simple two-d ...

The old DLL is causing a reference error when called upon

While working with a TwitchLib reference and utilizing Newtonsoft.Json 7.0.0, I encountered an error every time I visited the page that calls Twitch lab. The error message displayed is: "Could not load file or assembly 'Newtonsoft.Json, Version=7.0.0 ...

Building a REST application using the CodeIgniter framework with database integration

I successfully created a REST app using CodeIgniter and a database by following the instructions provided at https://github.com/chriskacerguis/codeigniter-restserver. Everything works perfectly and it's wonderful. Currently, my JSON file shows static ...

Incorporating the "+ " icon in Vuejs Dropzone to indicate the presence of existing images

Looking to enhance my Vue-dropzone file uploader component by adding an icon or button labeled "Add more images" when there are already images present in the dropzone. This will help users understand that they can upload multiple photos. Any suggestions on ...

The DOMException occurred when attempting to run the 'querySelector' function on the 'Document' object

Currently, I am engaged in a project that was initiated with bootstrap version 4.3.1. I have a keen interest in both JavaScript and HTML coding. <a class="dropdown-item" href="{{ route('user.panel') }}"> User panel </a& ...

How to send a JavaScript variable to Flask and trigger an AJAX reload action

Introduction: I have explored similar inquiries and attempted to apply relevant code/concepts but without success. -https://stackoverflow.com/questions/43645790/passing-javascript-variable-to-python-flask -https://stackoverflow.com/questions/10313001/is- ...

Exploring the depths of JSON parsing with Java's speedy FastXML library

Experimenting with a Java program to test JSON Processing using the org.fasterxml.jackson.core and the jackson-databind libraries in a streaming manner. The main objective is to understand how to handle JSON data and extract specific information. Currently ...

switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue: let bulbImage = $.querySelector(".bulb-image"); let turnOnOption = $.querySele ...

Partial implementation of jQuery datepicker feature facing technical issues

Greetings, I have a functional datepicker implemented in my code as follows: <link rel="stylesheet" href="uidatepicker/themes/blitzer/jquery.ui.all.css"> <script src="uidatepicker/jquery-1.5.1.js"></script> <script src="uidate ...

How can I ensure that $routeProvider functions correctly within my AngularJS application?

I'm currently in the process of manually constructing a shell and trying to understand its functionality Shell Structure: - application (contains PHP files) - webroot -- app --- app.js -- templates --- main ---- login ----- login.html index.html ...

Element dynamically targeted

Here is the jQuery code I currently have: $('.class-name').each(function() { $(this).parent().prepend(this); }); While this code successfully targets .class-name elements on page load, I am looking to extend its functionality to also target ...

What purpose does the additional symbol "$()" serve in the selector "$($())"?

Currently, I am looking to incorporate a jQuery scrollspy feature into one of my ongoing projects. Upon coming across this jsfiddle (https://jsfiddle.net/mekwall/up4nu/), I successfully integrated it into my project. However, I have hit a roadblock while ...

The browser's window.location.href fails to redirect the page

Here are my functions: <a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a> function check_claims(ele){ var select_claims = document.getE ...

Using Material UI with Reactjs for Background Image Mapping

I need some advice from everyone. I have an array of images and I've mapped the content, but for some reason I am unable to set a background image in the styles of a component. The other objects in the array are working as expected. {DlCards.map((mdlc ...

Ways to correctly import various CSS files for individual routes in a Vuejs application

Currently, I am in the process of developing a project using Vue.js and Laravel. This project will have distinct layouts for the admin/user panel and landing page, requiring different CSS files to be loaded for each route. At the moment, I am utilizing va ...

Double Serialization with Java's Jackson Library

In my code, I have a class that includes a String field and a Map field. My goal is to serialize this class into JSON using Jackson. public class Mapping private String mAttribute; @JsonIgnore private Map<String, String> mMap; @J ...

What would be the JavaScript counterpart to python's .text function?

When using Element.text, you can retrieve the text content of an element. Recently, in a separate discussion on SO, there was a Python script discussed that scraped data from the followers modal of an Instagram account. The script is designed to capture t ...