【问题标题】:Getting data from a d3 CSV parse request back to the code body从 d3 CSV 解析请求中获取数据返回代码主体
【发布时间】:2016-02-14 16:45:18
【问题描述】:

我浏览了多个页面和示例,但这对我不起作用,所以我可能做错了一些非常明显的错误,但我终其一生都无法弄清楚:

d3.csv("example.csv", function(d) {
  return {
    year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
    make: d.Make,
    model: d.Model,
    length: +d.Length // convert "Length" column to number
  };
}, function(error, rows) {
  console.log(rows);
});

点击“函数(错误,行)”后,我的行记录得很好,并且加载成功。所以我试着做

var dataset = d3.csv(etc etc

并将 console.log 更改为

return rows;

或将 console.log 更改为

dataset = rows;

但是它不起作用,并且在请求之后立即,我无权访问数据。

【问题讨论】:

    标签: javascript csv d3.js


    【解决方案1】:

    d3.csv 不会像您尝试那样返回数据供您分配。原因是d3.csv是一个异步函数。

    异步函数不返回其结果。实际上,异步函数通常对应于潜在的长操作(就像在这种情况下加载可能很大的 csv 文件一样)。如果函数要在操作结束后才返回,以便它可以返回结果,那么浏览器会卡在等待操作而无法对任何其他用户输入做出反应(想象在等待时无法滚动)下载文件!)

    异步函数提供结果的一种常见方式是通过回调:作为参数传递的函数,当结果可用时将调用该函数,并将结果作为参数。您已经在使用此回调:这是执行日志记录的函数。

    因此,您的解决方案是将所有使用数据集的代码放在该回调中。像这样:

    d3.csv("example.csv", function(d) {
      return {
        year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
        make: d.Make,
        model: d.Model,
        length: +d.Length // convert "Length" column to number
      };
    }, function(error, dataset) {
      // put here the code that makes use the dataset
      // e.g. drawing a graph, or showing a table
    
      // you won't be able to use dataset out of this function!
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 2018-06-29
      相关资源
      最近更新 更多