Saher Ahwal
Saher Ahwal

Reputation: 9237

Asynchronous Function in Iteration - javascript

I am trying not to replicate code and loop over a a function in d3 that is asynchronous. Here is some code

Since d3.text is asynchronous , I am not able to use the index u in a correct way to append objects to the DOM. How should I go about this? I need the loop to go to next iteration once d3.text finished

for(var u in urls) {
  console.log(u);
  var url = "interest_points/" + urls[u] + ".csv";
  var data_gpBy_month = {};
  var sortable_month = []

  d3.text(url, function(text) {
    // some code...
    var data = d3.csv.parseRows(text).map(function(row) {
      //some code...        
    });

    //some code
  });           
}

Upvotes: 0

Views: 207

Answers (3)

meetamit
meetamit

Reputation: 25157

The loop should simply become this:

for(var u in urls) { loadParseAndRender(u); }

All your existing logic then moves into loadParseAndRender, but at this point u will never get overridden. I.e, in fancy terms, it gets captured in the closure.

function loadParseAndRender(u) {
  // the rest of your code
}

What David W suggested is the same thing as abive, but without creating a named function for it, you'd do this:

for(var _u in urls) {
  (function(u) { // this is an anonymous function
    // the rest of you code
  })(_u) // this function gets called as soon as it's declared 
}

Upvotes: 1

ZER0
ZER0

Reputation: 25322

If I understood properly:

function doSomething(array) {
  var u = array.shift();
  console.log(u);

  var url = "interest_points/" + urls[u] + ".csv";
  var data_gpBy_month = {};
  var sortable_month = []

  d3.text(url, function(text) {
    // some code...
    var data = d3.csv.parseRows(text).map(function(row) {
    //some code...        
    });

    //some code

    if (array.length > 0)
      doSomething(array); 
 });           


 doSomething(Object.keys(urls));

Upvotes: 0

pax162
pax162

Reputation: 4735

Something like this (fiddle: http://jsfiddle.net/EYAYT/2/) ?

var urls = ["asd", "asdasd", "Asdasfa"];
var currentUrlIndex = 0;
var getUrl = function(){
    if (currentUrlIndex >= urls.length){
        return null;
    } else {
      return "interest_points/" + urls[currentUrlIndex++] + ".csv";
    }
}

var execd3Text = function(){
    var url = getUrl();
    if (url){
        d3.text(url, function(text) {                                               

                  //some code;;
                  execd3Text();
                });
    }
}

execd3Text();

Upvotes: 1

Related Questions