【问题标题】:Why is my map function returning undefined when used within a promise?为什么我的 map 函数在 promise 中使用时返回 undefined?
【发布时间】:2020-04-11 16:46:45
【问题描述】:

我正在为 GDP 数据获取键值对(日期、值)的 JSON 对象。

我想从 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 对象中每个数组的第二个值。

JSON 源https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json

【问题讨论】:

  • console.log(dataset) 放入.then()。目前它在返回承诺之前被记录

标签: javascript json d3.js


【解决方案1】:

你需要在promise里面做console.log。

您在调用 d3.json 调用后立即调用了 console.log,该调用立即返回,但承诺随后发生。

【讨论】:

    【解决方案2】:

    这里有几个问题。 首先,正如 GTBebbo 提到的,将在 json 获取数据之前调用。 其次,您的数据是整个响应对象。所以会抛出错误。您可以使用对象解构从响应中获取数据数组

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-18
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多