gpt4 book ai didi

javascript - d3.json() 回调中的代码未执行

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:20 25 4
gpt4 key购买 nike

我正在尝试加载 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的签名有changed从 D3 v4 到 v5。它已从现已弃用的模块 d3-request 移至新的 d3-fetch模块。从 v5 开始,D3 使用 Fetch API支持旧的 XMLHttpRequest 并反过来采用 Promises处理这些异步请求。

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

您的代码因此变为:

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() 返回的 Promise 将被拒绝。因此,可以应用处理这些拒绝的普通 JS 方法:

  1. 传递拒绝处理程序作为第二个 argument.then(onFulfilled, onRejected)

  2. 使用.catch(onRejected)向 Promise 添加拒绝处理程序。

应用第二个解决方案,您的代码将变成

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

关于javascript - d3.json() 回调中的代码未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49946763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com