skip to Main Content

I am not expert in d3.js and i have to modify a program using it.

I have not found a good answer for my problem, i need to modify a file before to parse it: so i use this piece of code: (d3.js v4)

    d3.text(file, function (d) {
        //modify the content of file loaded
        d = d.replace(/ (édito)/g, "_edito")
            .replace(/ (startup)/g, "_startup");
        //parse after
        d3.csvParse(d, function (d) {
            console.log(d);
        });
    });
    console.log("next");

but the problem is d3.text, d3.csv are asynchronous and so console.log("next") is executed before the content of file line par line with console.log(d).

How i can wait the result of d3.txt ? before to continue…and without blocking the UI

2

Answers


  1. Chosen as BEST ANSWER

    in fact there is no problem, if i set all next codes in function

    d3.text(file, function (d) {
        //modify the content of file loaded
        d = d.replace(/ (édito)/g, "_edito")
            .replace(/ (startup)/g, "_startup");
        //parse after
        var result = d3.csvParse(d, function (d) {
            console.log(d);
            return d;
        });
        goToNext(result)
    });
    
    function goToNext(datas){
        console.log(datas);
    }
    

  2. If you’re reading a CSV file with D3 v4, then the recommend approach looks like so:

    d3.csv("file.csv", function(error, data) {
      if (error) {
        throw error
      }
      else {
        ... do something with data
      }
    });
    

    Note that the handler is a function of two variables, the first of which is any error that might be thrown. The same is true of d3.text, but you have only one variable in your code that doesn’t refer to the data, as you’d like.

    I guess you might be using version 4 of D3 because you’re dealing with legacy code or some such. The current version of v7, though, and there have been plenty of improvements. The API changed at v5 so that the suggested approach would now be.

    d3.csv("file.csv").then(function(data) {
      ... do something with data
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search