Code within d3.json() callback is not executed

后端 未结 1 1828
遥遥无期
遥遥无期 2020-11-22 08:04

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 ever

相关标签:
1条回答
  • 2020-11-22 08:50

    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...
      });
    

    Error handling of the call has also changed with the introduction of the Fetch API. Versions prior to v5 used the first parameter of the callback passed to d3.json() to handle errors:

    d3.json(url, function(error, data) { 
      if (error) throw error;
      // Normal handling beyond this point.
    });
    

    Since D3 v5 the promise returned by d3.json() will be rejected if an error is encountered. Hence, vanilla JS methods of handling those rejections can be applied:

    1. Pass a rejection handler as the second argument to .then(onFulfilled, onRejected).

    2. Use .catch(onRejected) to add a rejection handler to the promise.

    Applying the second solution your code thus becomes

    d3.json("/trip_animate/tripData.geojson")
      .then(function(data) {
        // Code from your callback goes here...
      })
      .catch(function(error) {
        // Do some error handling.
      });
    
    0 讨论(0)
提交回复
热议问题