使用 d3-fetch 模块加载多个文件 [英] Load multiple files using the d3-fetch module

查看:11
本文介绍了使用 d3-fetch 模块加载多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从两个不同的来源加载数据.加载数据后,我想在 riot 标记文件中使用它.但是我不明白如何加载第二个文件,因为我不太了解异步调用.

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

推荐答案

d3-fetch模块使用 Fetch API,因此将返回一个 Promise 用于通过模块之一发出的每个请求方便的方法.要一次加载多个文件,您可以使用 Promise.all 将返回一个 Promise,一旦提供给调用的所有 Promise 都已解决,该 Promise 就会解决.

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

这里提供了 d3.csvd3.json 来从两个文件中获取内容.一旦两个请求都完成了,即两个 Promise 都解决了,每个文件的内容提供给单个 Promise 的 .then() 方法调用.此时,您可以访问数据并执行其余代码.

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.

这篇关于使用 d3-fetch 模块加载多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆