问题描述
我一段时间以来一直在使用d3.js v4,并且我了解到Mike Bostock已用Promise本机JavaScript对象替换了v5版本中的d3.queue.我想与您确认一下我编写的这段代码是否正确地(异步地)排队了这些URL:
I've been using d3.js v4 for sometime now and I've learned that Mike Bostock has replaced the d3.queue in the v5 release with the Promise native JavaScript object. I would like to check with you if this code that I have written is properly queuing (asynchronously) these URL's:
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();
该代码似乎正常运行,但是,此代码是否正确,或者是否有更好的方法(最佳实践方法)与Promise.all和d3.js进行排队?捕获错误是否已正确实施?
The code seems to function properly, but, is this proper code or is there a better way (a best practice approach) for queuing with Promise.all and d3.js? Is the catch error properly implemented?
推荐答案
您可以大大简化该代码:您不可以将new Promise
与d3.json
一起使用,因为d3.json
本身会创建承诺.
You can simplify that code a lot: you don't net to use new Promise
with d3.json
, since d3.json
will itself create the promise.
因此,您可以这样做:
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're into the 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)
});
由于我无法在S.O中使用JSON文件.片段,请在以下bl.ocks中检查控制台:
Since I cannot use JSON files in the S.O. snippet, check the console in this bl.ocks: https://bl.ocks.org/GerardoFurtado/f08993c9c729b0b3452ef1803ad9dcbf/c4b45c5acce6033085a667cbb7d34203d15de0f0
这篇关于d3.js v5-Promise.all替换为d3.queue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!