简体   繁体   中英

Asynchronous Function in Iteration - javascript

I am trying not to replicate code and loop over aa 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
  });           
}

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();

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. Ie, 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 
}

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM