我正在尝试加载 GeoJSON 文件并使用它作为 D3 的基础来绘制一些图形v5.
问题是浏览器跳过了包含在d3.json()
称呼。我尝试插入断点来测试,但浏览器会跳过它们,我不明白为什么。
下面的代码片段。
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
调用自己。
的签名d3.json https://github.com/d3/d3-fetch#json has changed https://github.com/d3/d3/blob/master/CHANGES.md#changes-in-d3-50从 D3 v4 到 v5。它已从现已弃用的模块 d3-request 移至新的模块d3-fetch https://github.com/d3/d3-fetch模块。从 v5 D3 开始使用获取API https://fetch.spec.whatwg.org/有利于老年人XMLHttpRequest
并反过来采用了使用Promises https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise处理这些异步请求。
第二个参数d3.json()
回调不再处理请求,而是可选的RequestInit https://fetch.spec.whatwg.org/#requestinit目的。d3.json()
现在将返回一个您可以在其中处理的 Promise.then() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then method.
您的代码因此变为:
d3.json("/trip_animate/tripData.geojson")
.then(function(data){
// Code from your callback goes here...
});
随着 Fetch API 的引入,调用的错误处理也发生了变化。 v5 之前的版本使用传递给的回调的第一个参数d3.json()
处理错误:
d3.json(url, function(error, data) {
if (error) throw error;
// Normal handling beyond this point.
});
自 D3 v5 起,承诺返回d3.json()
如果遇到错误将被拒绝。因此,可以应用处理这些拒绝的普通 JS 方法:
将拒绝处理程序作为第二个传递argument https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Parameters to .then(onFulfilled, onRejected)
.
Use .catch(onRejected) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch向 Promise 添加拒绝处理程序。
应用第二个解决方案,您的代码就变成了
d3.json("/trip_animate/tripData.geojson")
.then(function(data) {
// Code from your callback goes here...
})
.catch(function(error) {
// Do some error handling.
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)