简体   繁体   English

迭代中的异步函数--javascript

[英]Asynchronous Function in Iteration - javascript

I am trying not to replicate code and loop over aa function in d3 that is asynchronous. 我试图不复制代码并循环在异步的d3中的函数。 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. 由于d3.text是异步的,我无法以正确的方式使用索引u将对象附加到DOM。 How should I go about this? 我该怎么办呢? I need the loop to go to next iteration once d3.text finished 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
  });           
}

Something like this (fiddle: http://jsfiddle.net/EYAYT/2/ ) ? 像这样的东西(小提琴: 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. 所有现有的逻辑然后移动到loadParseAndRender ,但此时u永远不会被覆盖。 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: 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 
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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