d3异步等待fetch.json不是函数

时间:2019-02-04 15:13:33

标签: javascript asynchronous d3.js promise

我正在使用d3-fetch库来使用 async / await ,但是我遇到以下错误:fetch.json不是一个函数。

它确实可以与d3.json()一起使用。

我在这里做什么错了?

    async function fetchAllData() {

    try {

        let data = await fetch.json('https://api.myjson.com/bins/1cpi9w');
        return data;

        console.log("Initial data: ", data);

        console.log("type of n: ", indicateType(data[0].n));

        let format = d3.timeFormat("%Y");


        //Nesting data by category
        let updatedData = d3.nest()
            .key(d => d.category)
            .sortValues((a, b) =>  a.year - b.year)
            .entries(data);

        //Define xScale domain (min,max assume it has been sorted by year)
        xScale.domain([
            d3.min(updatedData, function(s) { return s.values[0].year; }),
            d3.max(updatedData, function(s) { return s.values[s.values.length - 1].year })
        ]);

        console.log("Nested data: ", updatedData);



        //Draw an SVG for each country

    } catch (error) {
        console.log(error);
    }
}

const indicateType = unevaluatedOperand => typeof unevaluatedOperand;

fetchAllData();

1 个答案:

答案 0 :(得分:5)

获取是Web API的一部分。根据文档,调用fetch.json()并不起作用。

这是一个有效的示例:

async function fetchAllData () {
  // await response of a fetch call
  const response = await fetch('https://api.myjson.com/bins/1cpi9w');
  // once the promise is resolved convert the response to an object
  const data = await response.json();
  // your data has been converted to an object now)
  console.log('Initial data:', data);
  return data;
}

fetchAllData();

相关问题