Code within d3.json() callback is not executed

2019-01-01 14:20发布

问题:

I am trying to load a GeoJSON file and to draw some graphics using it as a basis with D3 v5.

The problem is that the browser is skipping over everything included inside the d3.json() call. I tried inserting breakpoints to test but the browser skips over them and I cannot figure out why.

Code snippet below.

d3.json(\"/trip_animate/tripData.geojson\", function(data) {

  console.log(\"It just works\");  // This never logs to console.

  //...all the rest
}

The code continues on from the initial console.log(), but I omitted all of it since I suspect the issue is with the d3.json call itself.

回答1:

The signature of d3.json has changed from D3 v4 to v5. It has been moved from the now deprecated module d3-request to the new d3-fetch module. As of v5 D3 uses the Fetch API in favor of the older XMLHttpRequest and has in turn adopted the use of Promises to handle those asynchronous requests.

The second argument to d3.json() no longer is the callback handling the request but an optional RequestInit object. d3.json() will now return a Promise you can handle in its .then() method.

Your code thus becomes:

d3.json(\"/trip_animate/tripData.geojson\")
  .then(function(data){
    // Code from your callback goes here...
  });