1

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

Frenchy
  • 16,386
  • 3
  • 16
  • 39
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Konrad May 24 '23 at 16:54
  • 1
    There are several issues with the suggested duplicate. - The question is over a decade old, - The question does not refer to D3 at all, - The are 41 answers, none of which refer to D3 either, - Many of the answers refer to outdated techniques. – Mark McClure May 25 '23 at 00:04

2 Answers2

1

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
});
Mark McClure
  • 4,862
  • 21
  • 34
0

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);
}
Frenchy
  • 16,386
  • 3
  • 16
  • 39