Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load multiple files using the d3-fetch module

I try to load data from two different sources. After loading the data I want to use it within a riot tag file. But I do not understand how to load the second file, because I do not really understand the asynchronous call.

What do I have to modify in my code to get the data? Right now, the second data object is undefined. Here is my code:

import { csv, json } from 'd3-fetch'
csv('/data/stations.csv', function (stations) {
  json('data/svg_data.json', function (svg) {
    return svg
  })
  stations.position_x = +stations.position_x
  stations.position_y = +stations.position_y
  stations.animation_time = +stations.animation_time
  stations.text_x = +stations.text_x
  stations.text_y = +stations.text_y
    return stations
  }).then(function (stations, svg) {
   mount('metro-app', {
     stations: stations,
     svg_data: svg
  })
})
like image 357
Felix Avatar asked Mar 12 '18 15:03

Felix


People also ask

How to load csv data in d3?

csv() We can load a csv file or csv data using d3. csv() method.

What is d3 fetch?

This module provides convenient parsing on top of Fetch. For example, to load a text file: const text = await d3. text("/path/to/file.

What does d3 CSV do?

js csv() Function. The d3. csv() function in D3. js is a part of the request API that returns a request for the file of type CSV at the specified URL.

What does d3 JSON return?

The function d3. json() is an asynchronous function that directly returns (with an undefined value I assume). Only when the data is received from the backend, the callback function you passed to it will be called.


1 Answers

The d3-fetch module makes use of the Fetch API and will, therefore, return a Promise for each request issued via one of the module's convenience methods. To load multiple files at once you could use Promise.all which will return a single Promise that resolves once all Promises provided to the call have resolved.

import { csv, json } from 'd3-fetch'

Promise.all([
  csv('/data/stations.csv'),
  json('data/svg_data.json')
])
.then(([stations, svg]) =>  {
  // Do your stuff. Content of both files is now available in stations and svg
});

Here, d3.csv and d3.json are provided to fetch content from two files. Once both requests have completed, i.e. both Promises have resolved, the content of each file is provided to the single Promise's .then() method call. At this point you are able to access the data and execute the rest of your code.

like image 111
altocumulus Avatar answered Oct 26 '22 04:10

altocumulus