d3.json() 回调中的代码未执行 [英] Code within d3.json() callback is not executed

查看:25
本文介绍了d3.json() 回调中的代码未执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载 GeoJSON 文件并使用它作为 D3 v5 的基础绘制一些图形.

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

问题是浏览器会跳过 d3.json() 调用中包含的所有内容.我尝试插入断点进行测试,但浏览器跳过了它们,我不知道为什么.

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.

下面的代码片段.

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

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

  //...all the rest
}

代码从最初的 console.log() 开始,但我省略了所有代码,因为我怀疑问题在于 d3.json 调用本身.

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.

推荐答案

的签名d3.json更改从 D3 v4 到 v5.它已从现已弃用的模块 d3-request 移至新的 d3-fetch 模块.从 v5 D3 开始,使用 Fetch API 来支持旧的 XMLHttpRequest 和反过来又采用了 Promises 的使用处理那些异步请求.

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.

d3.json() 的第二个参数不再是处理请求的回调,而是一个可选的 RequestInit 对象.d3.json() 现在将返回一个您可以在其 .then() 方法.

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.

你的代码就变成了:

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

随着 Fetch API 的引入,调用的错误处理也发生了变化.v5 之前的版本使用传递给 d3.json() 的回调的第一个参数来处理错误:

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

从 D3 v5 开始,如果遇到错误,d3.json() 返回的承诺将被拒绝.因此,可以应用处理这些拒绝的普通 JS 方法:

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. 将拒绝处理程序作为第二个参数.then(onFulfilled, onRejected).

使用.catch(onRejected) 向承诺添加拒绝处理程序.

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

这篇关于d3.json() 回调中的代码未执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆