【问题标题】:trying to call a named function with async javascript then然后尝试使用异步 javascript 调用命名函数
【发布时间】:2022-01-23 07:11:07
【问题描述】:

我正在使用 d3.csv() 从 csv 文件加载数据。我试图在返回数据后调用一个命名函数,但这似乎不起作用。它给了我以下错误:

未捕获的引用错误:在初始化之前无法访问“驾驶”

let driving = d3.csv("./driving.csv").then( ConnectedScatterplot(driving, {
    x: d => d.miles,
    y: d => d.gas,
    title: d => d.year,
    orient: d => d.side,
    yFormat: ".2f",
    xLabel: "Miles driven (per capita per year) →",
    yLabel: "↑ Price of gas (per gallon, adjusted average $)",
    width:600,
    height: 720,
    duration: 5000 // for the intro animation; 0 to disable
  })) ;

如果我执行以下操作:

let driving = d3.csv("./driving.csv").then(function (driving) { ConnectedScatterplot(driving, {

它没有错误并且有“驱动”可用,但它也没有做我想要的,即使用参数调用 ConnectedScatterplot。

【问题讨论】:

  • 我不知道 d3.csv,所以对此无能为力,但要找出它实际产生的结果,您可以将代码简化为 d3.csv("./driving.csv").then(data => console.log(data)); 并查看结果。或者尝试使用console.table(data) 而不是console.log(data) 来查看对象的详细信息。如果在浏览器中运行,则在此之前使用 F12 打开开发工具。

标签: javascript d3.js async-await


【解决方案1】:

看来d3.csv()返回了一个Promise,那么我们有两种方式来处理csv函数的结果:

正如你所做的那样,只需在 then 块中调用 ConnectedScatterplot

d3.csv("./driving.csv").then((driving) => { // let driving is redundant
    ConnectedScatterplot(driving, {...});
})

如果你在一个异步函数中,你可以使用await语法:

(async () => { // async function
    const driving = await d3.csv("./driving.csv"); // await
    ConnectedScatterplot(driving, {...});
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-04
    • 2021-08-17
    • 2012-02-25
    • 2015-11-29
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多