迭代中的异步函数--javascript

时间:2013-11-11 17:34:50

标签: javascript asynchronous callback d3.js

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

由于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
  });           
}

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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 
}

答案 2 :(得分: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));