0

I have a question for my application logic in d3.js. I send an ajax request(some json data) from client to server and in the server(nodejs) I save into a file. Then I try to fetch json data via the following command.

        d3.json("nodes.json", function(error, json) {
        if(error)
        {
            console.warn('nodes.json error', error);
            //throw error;
        }
        console.log("d3.json");
        savedNodesLinks = json;
    });
    console.log('parsed', JSON.parse(JSON.stringify(savedNodesLinks || null)));
    if(JSON.parse(JSON.stringify(savedNodesLinks || null)) != null)
    {
        links = JSON.parse(JSON.stringify(savedNodesLinks || null)).links;
        nodes = JSON.parse(JSON.stringify(savedNodesLinks || null)).nodes;
    }

This function which consists above-mentioned code snippet is called by a button. When I click the button first time, 'savedNodesLinks' variable shows as an undefined. When I push the button second time, data comes in a robust way. How can I fix this issue? I debugged the code but I couldn't find the problem

Thanks in advance,

1
  • The d3.json() call is asynchronous, meaning it doesn't get the json right away. When the json is available the function where you have your console.log("d3.json") is called. At that point it is available. Meantime your console.log() call after d3.json() is called (before your json is available), so savedNodesLinks is not yet defined. I would suggest reading up on asynchronous calls in javascript to better understand this. Commented Mar 9, 2017 at 22:42

1 Answer 1

1

savedNodeLinks is used outside the scope try using your code inmediatelly after saveNodesLinks = json.

Because console.log('parsed', ... will occur before actually server returns the nodes.json file

    d3.json("nodes.json", function(error, json) {
    if(error)
    {
        console.warn('nodes.json error', error);
        //throw error;
    }
    console.log("d3.json");
    savedNodesLinks = json;
    console.log('parsed', JSON.parse(JSON.stringify(savedNodesLinks || null)));
    if(JSON.parse(JSON.stringify(savedNodesLinks || null)) != null)
    {
        links = JSON.parse(JSON.stringify(savedNodesLinks || null)).links;
        nodes = JSON.parse(JSON.stringify(savedNodesLinks || null)).nodes;
    }
});

It's not about d3.js, it's about javascript asynchronous programming. Check Introduction to asynchronous JavaScript

Sign up to request clarification or add additional context in comments.

1 Comment

What do you mean try using your code immediately after saveNodesLinks=json?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.