0

I am quite new in javascript and I did not find the answer to my problem yet.

Actually I use a for loop to get the content of several csv files, and add each content to a global csvstring in order to download the total csv file at the end. But the content of each csv is obtained with d3.csv which is asynchronous, so if I update my total csvstring in d3.csv, I cannot use it to save the total csv afterwards since the csvstring is not updated yet. How should I do that ?

My code, which is not working, is the following :

//here is code to define the queries
csvstring = "";
for (i=0 ; i<queries.length ; ++i) {
  d3.csv(queries[i], function(data) {
    //here is code to format data as a csvstring and then
    csvstring += data_as_csvstring;
   }
});
//here is code to download csvstring as a csvfile

I hope I made myself clear, and I thank you in advance for your answer !

Mag

Magali
  • 5
  • 4
  • Possible solution: http://stackoverflow.com/questions/23690356/how-to-load-multiple-csv-files-and-use-them-mixed-with-each-other – Andy Feb 06 '15 at 17:17
  • [queue.js](https://github.com/mbostock/queue) makes cases where you have to retrieve an unknown number/a lot of data files easier. – Lars Kotthoff Feb 06 '15 at 18:05

1 Answers1

1

You could do some recursion and wait until you are on the last query to do something?

var getCsv = function(queries, csvstring, startAt, callback){
        d3.csv(queries[startAt], function(data) {
            csvstring += data_as_csvstring;
            if(index == queries.length){
                callback(csvstring);
            } else {
                getCsv(queries, csvstring, startAt++, callback);
            }
        });
    }

getCsv(queries, '', 0, function(csvstring){
        console.log(csvstring); //the complete string
    });
Simon Staton
  • 4,345
  • 4
  • 27
  • 49
  • Indeed this is a working solution ! Thank you for making me understand the notion of callback and the recursion is a really good idea ! – Magali Feb 09 '15 at 09:35