[英]Why is my map function returning undefined when used within a promise?
我正在获取 GDP 数据的键值对(日期、值)的 JSON object。
我想从 JSON 文件中创建一个仅包含值的数组,但是在以下上下文中使用 map 时我变得不确定:
let dataset; d3.json('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json').then(data => { dataset = data.map(each => each[1]) }); console.log(dataset);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
let dataset;
d3.json('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
.then(data => {
dataset = data.map(each => each[1])
});
console.log(dataset);
我尝试访问的 JSON 数据示例。
{
"errors": {},
"id": 120140,
"source_name": "Federal Reserve Economic Data",
"source_code": "FRED",
"code": "GDP",
"name": "Gross Domestic Product, 1 Decimal",
"urlize_name": "Gross-Domestic-Product-1-Decimal",
"display_url": "http://research.stlouisfed.org/fred2/data/GDP.txt",
"description": "Units: Billions of Dollars\nSeasonal Adjustment: Seasonally Adjusted Annual Rate\nNotes: A Guide to the National Income and Product Accounts of the United States (NIPA) - (http://www.bea.gov/national/pdf/nipaguid.pdf)",
"updated_at": "2015-12-14T20:00:28.561Z",
"frequency": "quarterly",
"from_date": "1947-01-01",
"to_date": "2015-07-01",
"column_names": [
"DATE",
"VALUE"
],
"private": false,
"type": null,
"premium": false,
"data": [
[
"1947-01-01",
243.1
],
[
"1947-04-01",
246.3
],
请注意,在这种情况下,我试图访问 obj.data 中的数据,并希望返回 JSON object 中每个数组的第二个值。
JSON 来源: https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json
您需要在 promise 中执行 console.log。
您在调用 d3.json 调用后立即调用了 console.log,该调用立即返回,但 promise 随后发生。
你在这里有几个问题。 首先,正如 GTBebbo 提到的,将在 json 获取数据之前调用。 其次,您的数据是整个响应 object。 所以会抛出错误。 您可以使用 object 解构从响应中获取数据数组
let dataset; const url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json"; d3.json(url) // process response from json function.then(({ data }) => { // At thi moment we have response with json data return data.map(each => each[1]); }).then(dataArray => { // here you can manipulate with data console.log(dataArray); }); // This console calls earlier than json responce processed console.log("dataset", dataset); // dataset = undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.