Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active June 11, 2018 03:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbostock/1696080 to your computer and use it in GitHub Desktop.
Save mbostock/1696080 to your computer and use it in GitHub Desktop.
Asynchronous Queue
license: gpl-3.0

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment