This is a demonstration of d3-queue, a tiny library for running asynchronous tasks with configurable concurrency. Here three external JSON files are loaded concurrently using d3-request, and then a ready
function renders the sum of their contents:
d3_queue.queue(2)
.defer(d3_request.json, "1.json")
.defer(d3_request.json, "2.json")
.defer(d3_request.json, "3.json")
.await(ready);
The concurrency of the queue is set to two, such that the first two files (1.json and 2.json) are loaded in parallel. When either of those files has loaded, a third request is made for 3.json. See the API reference for details.
If you’d rather not load these modules separately, they are available as part of D3 4.0.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
h1 {
text-align: center;
font-family: "Helvetica Neue";
font-size: 96px;
line-height: 350px;
}
</style>
<h1>1 + 2 + 3 = <span id="result">?</span></h1>
<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src="https://d3js.org/d3-dsv.v1.min.js"></script>
<script src="https://d3js.org/d3-request.v1.min.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>
<script>
d3.queue(2)
.defer(d3.json, "1.json")
.defer(d3.json, "2.json")
.defer(d3.json, "3.json")
.awaitAll(ready);
function ready(error, results) {
if (error) throw error;
document.querySelector("#result").textContent = results.reduce(sum, 0);
}
function sum(p, v) {
return p + v;
}
</script>
1
2
3