D3.js v5 - Promise.all replaced d3.queue

I am using d3.js v4 at some point, and I found out that Mike Bostock replaced d3.queue in v5 using the built-in Promise JavaScript object. I would like to check with you if this code that I wrote correctly executes the sequence (asynchronously) of these URLs:

var makeRequest = function() { "use strict"; var bli = [ "http://stats.oecd.org/sdmx-json/data/BLI2013/all/all", "http://stats.oecd.org/sdmx-json/data/BLI2014/all/all", "http://stats.oecd.org/sdmx-json/data/BLI2015/all/all", "http://stats.oecd.org/sdmx-json/data/BLI2016/all/all", "http://stats.oecd.org/sdmx-json/data/BLI/all/all" ]; var promises = []; bli.forEach(function(url) { promises.push( new Promise(function(resolve, reject) { d3 .json(url) .then(function(response) { resolve(response); }) .catch(function(error) { console.log("Error on: " + url + ". Error: " + error); reject(error); }); }) ); }); Promise.all(promises).then(function(values) { console.log(values); }); }; makeRequest(); 

The code seems to work correctly, but is this the right code or is there a better way (best practice approach) for queues using Promise.all and d3.js? Is the catch error executed correctly?

+5
source share
1 answer

You can simplify this code: you cannot use new Promise with d3.json , since d3.json will create a promise itself.

So you can just do:

 var files = ["data1.json", "data2.json", "data3.json"]; var promises = []; files.forEach(function(url) { promises.push(d3.json(url)) }); Promise.all(promises).then(function(values) { console.log(values) }); 

Or, if you are in code golf , even shorter:

 var files = ["data1.json", "data2.json", "data3.json"]; Promise.all(files.map(url => d3.json(url))).then(function(values) { console.log(values) }); 

Since I cannot use JSON files in SO snippet, check the console in this bl.ocks: https://bl.ocks.org/GerardoFurtado/f08993c9c729b0b3452ef1803ad9dcbf/c4b45c5acce6033085a667cbb7d34203d15de0f0

+6
source

Source: https://habr.com/ru/post/1276131/


All Articles