Include a predetermined parameter for the upcoming callback

Currently, I am working on loading files asynchronously by utilizing d3's queue, defer, and await features. The issue arises when I attempt to execute this process in a loop, where for each iteration, I aim to store the retrieved data in a dictionary:

var myDictionary = {};

// For example, hierarchy = ["State", "County"]
hierarchy.forEach(function(geo) {
    queue()
      .defer(d3.json, 'assets/data/geo/' + geo + '/' + geo + '.json')
      .defer(d3.csv,  'assets/data/geo/' + geo + '/' + geo + '_info.csv')
      .await(myFunc);
});

function myFunc(error, jsonData, csvData) {
    // It is crucial to have access to the 'geo' variable
    console.log(geo);

    myDictionary[geo].jsonData = jsonData;
    myDictionary[geo].csvData  = csvData;
}

Within myFunc, the challenge lies in obtaining access to 'geo' in order to correctly populate the dictionary keys. Passing it through .await.myFunc(geo) results in 'undefined' being printed inside myFunc.

I am uncertain whether this dilemma is related to Javascript's callback functions, D3's await() method, or both.

Do you have any suggestions or recommendations?

Thank you

Answer №1

Here is a helpful function:

function handleData(geolocation) {

    return function(error, jsonData, csvData) {
        // access geo here
        console.log(geolocation);

        myData[geolocation].jsonData = jsonData;
        myData[geolocation].csvData  = csvData;
    };
};

Next:

var myData = {};

// example hierarchy = ["City", "District"]
hierarchy.forEach(function(geolocation) {
    queue()
      .defer(d3.json, 'assets/data/geo/' + geolocation + '/' + geolocation + '.json')
      .defer(d3.csv,  'assets/data/geo/' + geolocation + '/' + geolocation + '_info.csv')
      .await(handleData(geolocation));
});

Answer №2

One option is to include it as a task so that it can be passed into your myFunc.

queue()
  .defer(d3.json, 'assets/data/geo/' + geo + '/' + geo + '.json')
  .defer(d3.csv,  'assets/data/geo/' + geo + '/' + geo + '_info.csv')
  .defer(callback=>callback(geo))
  .await(myFunc);
...
function myFunc(error, jsonData, csvData, geo) {
    console.log(geo);
}

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

Do not allow negative values to be displayed in the text box

Plunker I need to restrict negative values from being entered into a text field. If the user tries to input a negative value, I want the text box to remain unchanged. Although I have a directive that prevents negative values from being entered, it seems ...

Is the ajax success function failing to work properly in JavaScript?

Although I've searched extensively on Stack Overflow, none of the similar questions seem to solve my issue. The problem I'm facing is that the success function is not triggering the alert message and I can't seem to figure out why. <form ...

Trigger a unique event using Vanilla JS and then detect it on Vue instances

I am currently in the process of incorporating multiple Vue instances into my website. I have encountered issues preventing me from making the entire website a Vue instance and using components due to potential conflicts and other complications. For examp ...

Transform the event information based on specific configuration settings

I possess an array containing JSON data named config. var config = [ [{'state': 'step1'}], [{'state': 'step2'}] , [{'state': 'step3'}] ]; The data ...

Converting Markdown to HTML using AngularJS

I'm utilizing the Contentful API to retrieve content. It comes in the form of a JSON object to my Node server, which then forwards it to my Angular frontend. This JSON object contains raw markdown text that has not been processed yet. For instance, t ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...

Struggling to make EJS button functional on the template

I am currently facing an issue with a loop that populates a webpage with multiple items, each containing an image, text, button, and a unique ID associated with it. Although I have written a function to retrieve the ID and plan name when the button is clic ...

Determine the total hours and minutes elapsed between two specific dates and times

Looking for some assistance here. I have a form where users need to input a start time and end time of an incident. After entering this information, they would manually calculate the duration between the two date times. I am attempting to streamline this p ...

Adjust the size of a div by clicking a button using Javascript

<script type="text/javascript"> var btn = document.getElementById("btn"); var panel = document.getElementById("panel"); var btn2 = document.getElementById("btn2"); function expandPanel() { btn.style.display="none"; panel.style="overflow:hidd ...

What are the techniques used to minimize JavaScript functions?

Is there a more efficient way to reduce the amount of JavaScript code needed for functions that share the same call procedure? I'm struggling to find a clear explanation but here's the code snippet below... JavaScript: $(function() { $( &a ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

javascript increment variable malfunctioning

Below is the script I am working with: $(function() { var fileCount = {{$image_counter}}; $('#remove-file').click(function() { fileCount--; }); if (fileCount >= '5'){ $("#d ...

Normalization of Firebase Database

Recently, I developed a Tricycle Patrol app designed to address the prevalent issue of reckless tricycle drivers in our city. Users can log in and submit reports through a form that includes fields such as: - created_at - description - lat - lng - plateNu ...

Is it possible to use nodemailer locally with NodeJS? The issue is that the greeting emails are not being received

Every time I attempt to send an email using nodemailer within my local network, I encounter the following error: *Greeting never received at SMTPConnection._formatError (C:\Users\PI_TEAM\Desktop\node_modules\nodemailer\lib ...

Generate a new web component using JavaScript

My HTML table looks like this: <table id = "rpttable" name = "rpttable"> <thead> Column Headers here... </thead> <tbody id = "rptbody" name = "rptbody"> data here <3 .... </tbody> </table> And in my ...

javascript Why isn't the initial click registering?

In my table, users can select certain rows by using checkboxes. I have implemented some JavaScript functionality that allows them to select each checkbox individually and also use a "Select All" option. Additionally, there is code written to enable the use ...

What was the reason for needing to employ `toObject()` in mongoose to determine if an object contains a certain property?

From what I understand, there is no .toObect() function in JavaScript, but it is used in mongoose to convert mongoose documents into objects so that JavaScript built-in functions can be used. I sometimes struggle with when to use it. There are instances w ...

Incorporating React-Native components into a Next.js application within an Nx monorepository: A Step-by-Step

I'm encountering an issue while attempting to integrate React Native components into an Nx monorepo setup. Initially, the Nextjs app compiles successfully: info - Fast Refresh enabled for 1 custom loader event - client and server compiled successful ...

Nesting placeholders is not permitted in i18n

I am attempting to implement Interpolation with Vue3 and vue-i18n version 9.3. However, when I try to pass arguments, I encounter the following error: Message compilation error: Not allowed nest placeholder 1 | Showing {{from}} to {{to}} of {{total}} ent ...