【问题标题】:Variable is undefined after fetching json content [duplicate]获取json内容后变量未定义[重复]
【发布时间】:2021-04-10 09:27:47
【问题描述】:

我正在尝试将 json 内容从本地文件传递到变量,以便动态地提供下拉列表。如果我对 json 数据进行硬编码,下面的代码可以正常工作,但是我很难初始化从本地文件接收 json 的变量...我获取它,在控制台中打印它,但是我的 var之后仍然未定义。

https://jsfiddle.net/ssoj_tellig/zo85r30x/10/

// test to pass json content to var mydates:
var mydata;    
fetch("{% static 'dates.json' %}")
.then(function(u){return u.json();})
.then(function(json){mydata = json; console.log(mydata)})

// test to see if mydates is correctly initialized, this should print in the console: 2018, 2019, 2020 ... not working
for (let year in mydata){                  
    console.log(year)
}

我已阅读以下文章,但无济于事(我仍然难以理解如何解决它):

What is the scope of variables in JavaScript?

How do I return the response from an asynchronous call?

非常感谢您的帮助!

【问题讨论】:

标签: javascript


【解决方案1】:

fetch 调用是异步处理的,而你的 for 循环是同步调用的。要解决此问题,您应该在最后一次 .then 调用中包含循环。

fetch("{% static 'dates.json' %}")
  .then(function(u){return u.json();})
  .then(function(json){
    for (let year in mydata){                  
      console.log(year);
    }
  });

【讨论】:

  • 或者更好的是,定义一个可以做任何你想做的事情的函数——然后在那个时候使用它。
  • @sheriffderek:为什么会更好?
  • 因为它会封装逻辑,并且 .then 块不会变成一团糟。它还将迫使设计师将含义抽象为清晰简洁的可堆肥指令。 jsfiddle.net/sheriffderek/c5se17fm 但是,嘿-也许不是更好。你可以编写所有没有函数的代码。
猜你喜欢
  • 2015-08-13
  • 2015-08-13
  • 2017-04-02
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多