【问题标题】:FETCH API return undefinedFETCH API 返回未定义
【发布时间】:2017-03-29 17:36:09
【问题描述】:

我想使用 Fetch API,但我不太了解它的机制。

我的 HTML 中有一个,我想用这段代码分配我的提取结果:

const weather = "http://api.apixu.com/v1/current.json?key=cba287f271e44f88a60143926172803&q=Paris";
const array = [];

fetch(weather)
.then(blob => blob.json())
.then(data => {
  array.push(data.current.humidity)
  console.log(array[0])
      }
);
 document.querySelector('h1').innerHTML = array[0]; 

我有 console.log 的结果,但返回“未定义”。你能解释一下为什么吗?

非常感谢

【问题讨论】:

    标签: api undefined fetch


    【解决方案1】:

    这是因为对 API 的调用是异步,这意味着代码不会在您编写时逐行执行。回调仅在对 API 的调用完成后才运行,基本上意味着

    data => {
      array.push(data.current.humidity)
      console.log(array[0])
    }
    

    之后运行

    document.querySelector('h1').innerHTML = array[0];
    

    因此,当您尝试设置 h1 时,array 仍然为空。如果您想在数据可用时立即设置,则必须在回调函数中进行:

    data => {
      array.push(data.current.humidity)
    
      document.querySelector('h1').innerHTML = array[0];
    }
    

    起初这可能看起来很奇怪,但请记住,您只是注册了一个匿名函数,但还没有运行它。您只需定义要在发生某事时立即触发的函数,在这种情况下:当您的 API 调用完成时。

    【讨论】:

      猜你喜欢
      • 2017-11-12
      • 2021-05-21
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多