简体   繁体   English

将 d3.queue 与 D3 v5 一起使用

[英]Using d3.queue with D3 v5

I know that d3.queue() has been replaced with Promise in D3 version 5, indeed if I try to use the function I get:我知道d3.queue()在 D3 版本 5 中已被Promise取代,事实上,如果我尝试使用 function 我得到:

d3.queue is not a function d3.queue 不是 function

But I don't understanding why if I put this in the html header I don't get the above error anymore, but the code seems not working:但我不明白为什么如果我把它放在 html header 我不再收到上述错误,但代码似乎不起作用:

<head>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="https://d3js.org/d3-queue.v3.min.js"></script>
</head>

TL;DR : You simply don't need d3.queue in D3 v5 because it uses the Fetch API internally. TL;DR :您根本不需要 D3 v5 中的d3.queue ,因为它在内部使用Fetch API Therefore, you can just use things like Promise.all() or chaining the then() methods.因此,您可以只使用Promise.all()或链接then()方法。


As you probably know, d3.queue was meant to be used with D3 v4, not D3 v5.您可能知道, d3.queue旨在与 D3 v4 一起使用,而不是与 D3 v5 一起使用。 Since there is no queue method in D3 v5, just trying d3.queue will, as expected, result in the d3.queue is not a function error.由于在 D3 v5 中没有queue方法,因此仅尝试d3.queue将如预期的那样导致d3.queue is not a function错误。 When you reference the mini-library, the error obviously goes away.当您引用迷你库时,错误显然消失了。

It's worth mentioning that d3.queue will work if used with D3 v5, that's not an issue:值得一提的是,如果与 D3 v5 一起使用, d3.queue将起作用,这不是问题:

 d3.queue().defer(function foo(callback) { setTimeout(function() { callback(null, "finished"); }, 100); }).await(function(error, message) { console.log(message); });
 <script src="https://d3js.org/d3.v5.min.js"></script> <script src="https://d3js.org/d3-queue.v3.min.js"></script>

However, if for whatever reason you still want to use d3.queue with D3 v5 for fetching files , you have to pass the adequate function to defer , with the callback like this (here I'm using a simple JSON I created online, which is just {foo: 42} ):但是,如果出于某种原因您仍想使用d3.queue和 D3 v5 来获取文件,则必须将足够的 function 传递给defer ,并使用这样的回调(这里我使用的是我在线创建的简单 JSON ,只是{foo: 42} ):

 d3.queue().defer(function foo(url, callback) { d3.json(url).then(function(file) { callback(null, file) }) }, "https://api.npoint.io/5b22a0474c99d3049d2e").await(function(error, message) { console.log(message); });
 <script src="https://d3js.org/d3.v5.min.js"></script> <script src="https://d3js.org/d3-queue.v3.min.js"></script>

The reason is that, unlike D3 v4 or lower, in D3 v5 methods like d3.csv , d3.json , d3.tsv etc do not have a callback as the second (last) argument.原因是,与 D3 v4 或更低版本不同,在 D3 v5 方法中,如d3.csvd3.jsond3.tsv等没有回调作为第二个(最后一个)参数。 Instead of that, they return a promise (using the Fetch API).取而代之的是,它们返回 promise(使用 Fetch API)。

That being said, the snippet above is not only ugly but completely unnecessary: just drop d3.queue .话虽如此,上面的代码片段不仅丑陋而且完全没有必要:只需删除d3.queue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM