score:1
I would suggest you do it with a recursive function.
In the following example you can use loadFilesAndCalculateSum()
like the d3.text()
but instead of one string it takes an array of strings and the callback gets the calculated sum instead of the text of a file.
/**
* load all files and calculate the sum of the values
* @param {Array} filenames Array with filenames as string
* @param {Function} cb Callback function, gets the sum as param
* @param {number} sum The initial sum
* @param {number} i Starting index for filenames
* @return {void}
*/
function loadFilesAndCalculateSum(filenames, cb, sum, i) {
sum = sum || 0;
i = i || 0;
d3.text(filenames[i], function(error, text) {
//parse the rows and reduce them
sum += d3.csv.parseRows(text).reduce(function(prev, curr) {
//return previous sum + this rows sum
return prev + d3.sum(curr, function(d){return +d;})
},0);
if(i < filenames.length - 1){
//load next file
loadFilesAndCalculateSum(filenames, cb, sum, i+1);
} else {
//call the callback with the final sum
cb(sum);
}
});
}
var filenames = ["file1.txt", "file2.txt", "file3.txt"];
loadFilesAndCalculateSum(filenames, function(sum){
//do something with the total sum
console.log(sum);
});
To clarify this. you have to do the processing of sum inside of the callback function where I put the comment do something with the total sum
. This function is still executing async. That means, that everything you write after the loadFilesAndCalculateSum()
function will possibly execute before the code inside the callback. You can find a little longer introduction to async javascript here
//this is executed first
//....
loadFilesAndCalculateSum(filenames, function(sum){
//do something with the total sum
//this is executed third, when all files are loaded and the sum is calculated
console.log(sum);
});
//code after this point is executed second, while the files are being loaded.
If you already have a function that does something with the sum, you can pass this function to the loadFilesAndCalculateSum
as second parameter. This is possible because functions are so called first class citizens:
var addthis = 5;
function doSomethingWithTheSum(sum) {
//everything you want to do with the sum goes inside this function.
//from here you could call other functions and pass the sum.
soSomethingDifferentWithTheSum(sum);
//or you use the sum inside this function
console.log(sum);
var newsum = sum + addthis;
console.log(sum);
d3.select("whatever")
.data([sum])
.enter()
.append("text")
.text(function(d){ return d;});
}
loadFilesAndCalculateSum(filenames, doSomethingWithTheSum);
You can pass functions just like any other variable. in the first example I called the second parameter of the loadFiles...
function cb
which is the usual abbreviation for callback
. As stated in the doc comment, this param should be of type Function
.
In the end of the loadFiles...
function I the callback function gets called by
....
//call the callback with the final sum
cb(sum);
....
Here the sum is given to the callback function as first parameter. Therefore if you pass a function, it should take a single param, like the anonymous function in the first example or the doSomethingWithTheSum
function in the example above.
Source: stackoverflow.com
Related Query
- Load and parse multiple csv files with D3.js
- dc.js with crossfilter and d3, how to load multiple csv files at once, without knowing how many files the user will upload
- How to load multiple csv files and use them mixed with each other
- D3.js: Load flat 1-dimensional array via d3.csv results in "TypeError: groupData is undefined" / Load multiple CSV files with D3.js
- How to load multiple files with Queue.js and D3.js?
- D3.JS how to load 3 csv files and change data on line chart with button click event?
- D3.js: Set fitExtent or fitSize (or center and scale programmatically) for map with multiple geoJSON files
- Using queue() to load multiple files and assign to globals
- How to load 30 csv files in parallel using queuejs with d3js?
- how to load csv file with vue.js and d3.js
- combining multiple geojson files w tsv and preserving property with topojson
- Importing data from multiple csv files in D3
- Load multiple files using the d3-fetch module
- Javascript: Load csv file and print it to page
- Loading multiple CSV in DC.js, adding a value, and concatenating the results into a single dataTable
- D3.js - Donut charts with multiple rings and animation transition
- How To Move (Drag and Drop) multiple Shapes with D3
- Load local .csv with js and process it with d3.js
- reading nodes and edges from two distinct csv files using Force Layout
- Loading Multiple CSV files in Javascript
- Trying to load simple CSV file into D3 with queue.js
- D3: Loading multiple csv data files in a folder
- Data structure for a family tree with multiple partners and siblings?
- Multiple maps with d3.js: change values of scale and center
- Load and modify svg files from node.js
- D3, Flask, Pythonanywhere, problems with csv files
- Load CSV file in DC.JS with D3.csv
- 404 error trying to parse csv with javascript/D3
- D3.js join data from multiple csv files
- D3 Bar and Linear Chart With Multiple Axis
More Query from same tag
- d3 functions not working in node.js when rendering charts from the server side
- Highlight all connected paths from start to end of a sankey diagram using networkD3
- How to change d3.js text entry from within that text's onclick method?
- D3 Logarithmic Tick Labels as Powers of 10
- watchTransition() is not a function in nv.d3.js with angular.js
- Add Labels to D3.JS Decision Tree Path
- TreeMap not working with JSON
- TypeScript : Argument Type Function is not assignable to parameter type function
- D3 v4 Zoom x-Axis Zooming and Panning Issue
- D3 Transition: Rotation and Translation
- Chaining transitions using the transition.end() promise
- D3 function to wrap text fails in tabbed display
- d3.js how to dynamically add nodes to a tree
- D3 Brush and Zoom error
- JavaScript: "SyntaxError: missing ) after argument list" last line of file
- How to draw a diamond with the path "d" attribute?
- d3 adding drag and drop to packed circles
- d3 - creating lookup with nest/group
- read external coordinates of a converged force directed graph in d3.js v4
- Cannot have multiple charts in one HTML page - d3
- Sweep direction of arc in ring diagram
- How do you retrieve the key values of a nested data set in D3
- Highcharts - timeseries chart with y-axis values need to be group with text labels
- how to plot the image inside the polygon in d3
- Changing slider color
- D3 ,update to a two level element
- Deep clone a function in javascript
- Omitting trailing zeroes / using sigfigs with d3.format()
- Leaflet.js: Pass feature property to class constructor
- Organizing data for grouped bar chart