0

我试图不复制代码并循环 d3 中异步的 aa 函数。这是一些代码

由于 d3.text 是异步的,我无法以u正确的方式使用索引将对象附加到 DOM。我该怎么办?一旦 d3.text 完成,我需要循环进入下一次迭代

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

3 回答 3

1

像这样的东西(小提琴: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();
于 2013-11-11T17:46:05.000 回答
1

循环应该简单地变成这样:

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

然后,您所有现有的逻辑都将移至loadParseAndRender,但此时u永远不会被覆盖。即,用花哨的术语来说,它在闭包中被捕获。

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

David W 的建议与 abive 相同,但如果不为其创建命名函数,您可以这样做:

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 
}
于 2013-11-11T17:58:10.673 回答
0

如果我理解正确:

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));
于 2013-11-11T17:46:11.290 回答