Skip to content Skip to sidebar Skip to footer

Getting Data Using D3.json() Is Not Working, While It Works Using Js Async Await.. Why?

I am trying to get some data from url to work with in d3.js. I can't seam to get the data using d3.json(url, callback). While it works fine when I use (ES8) async await function. C

Solution 1:

According to the documentation, d3.json returns a promise, like fetch does, rather than accepting a callback. (Edit: Apparently in v4 it accepted a callback — that explains it.) If you use that promise, it works.

You can either use the promise via async/await as you did with fetch, or by using then and (since you're not returning the chain to anyone else who would handle it) catch.

async/await:

(asyncfunction() {
  try {
    const jsonResponse = await d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json");

    const data = jsonResponse.data; // array of dates and valuesconst lowestVal = d3.min(data, d => d[1]);
    const highestVal = d3.max(data, d => d[1]);

    console.log(lowestVal);
    console.log(highestVal);
  } catch(error) {
    console.log(error);
  }
})();
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

then/catch:

d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json")
.then(json => {
  
     const data = json.data; // array of dates and valuesconst lowestVal = d3.min(data, d => d[1]);
     const highestVal = d3.max(data, d => d[1]);
     
     console.log(lowestVal);
     console.log(highestVal);
})
.catch(error => {
    console.error(error);
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Post a Comment for "Getting Data Using D3.json() Is Not Working, While It Works Using Js Async Await.. Why?"