最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Load multiple files using the d3-fetch module - Stack Overflow

programmeradmin0浏览0评论

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
  })
})

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
  })
})
Share Improve this question edited Mar 12, 2018 at 17:13 altocumulus 21.6k13 gold badges64 silver badges86 bronze badges asked Mar 12, 2018 at 15:55 FelixFelix 1,0172 gold badges14 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

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.

发布评论

评论列表(0)

  1. 暂无评论