【问题标题】:array returns length of 0 although it has values数组返回长度为 0,尽管它有值
【发布时间】:2019-07-19 12:44:45
【问题描述】:

所以我试图将项目推送到数组中,尽管数组中有项目,但它似乎返回的长度为 0。

let calendarDates = []

async function getDates() {
    const response = await fetch('/calendars/fetch_dates')
    let res = await response.json()
    res.forEach(el => {
        calendarDates.push(el)
    })
}

getDates()
createCalendar(date, side)
.
.
.

function createCalendar(date, side) {
    console.log('createCalendar', calendarDates, "is array?", Array.isArray(calendarDates), 'length', calendarDates.length)
.
.
}

我的 console.log 正在打印 calendarDates 和 length : array

console log for length

console.log 存在于一个单独的函数中

那么为什么它返回 0 的长度? 当尝试控制台记录一个 forEach 循环时,也没有任何返回,所以我不认为浏览器显示错误的乐趣值

【问题讨论】:

  • 你把你的console.log放在哪里?
  • @YongQuan 更新了我的代码 sn-p 以显示控制台日志的位置
  • getDates 是一个异步函数,而 createCalendar 是一个同步函数。因此 createCalendar 将首先被调用,并在 getDates 函数获取异步数据之前尝试读取数组的长度。
  • 我相信您所看到的不一致之处在于 console.log() 的工作方式(至少在 Chrome 中)。 createCalendar()getDates 完成之前被调用,但console.log() 被延迟并使用calendarDates 的后一个值...我不知道我是否解释正确.. 就像console.log 计算参数但是因为 calendarDates 是一个数组,所以它是通过引用传递的。因此,您不能相信日志中的值与实际调用时的值相同。

标签: javascript async-await


【解决方案1】:

这会有所帮助

async function Main() {
  let calendarDates = []
  calendarDates = await getDates();
  createCalendar(date, side)
}

async function getDates() {
  const response = await fetch('/calendars/fetch_dates')
  return await response.json();
}

function createCalendar(date, side) {
  console.log('createCalendar', calendarDates, "is array?", Array.isArray(calendarDates), 'length', calendarDates.length);
}


Main();

【讨论】:

  • 尝试向 OP 解释为什么您的代码有效但他的无效。
【解决方案2】:

getDates 是异步函数。所以,如果你打电话:

getDates()
createCalendar(date, side)

createCalendar 可能在 getDates() 成功之前被调用。 Async、Promise 真的很重要,你应该仔细练习和学习它们。

【讨论】:

  • 日历日期 = 等待 getDates();创建日历(日期,边);我们已经将await 用于getDates 函数,所以createCalendar 函数将不会被调用,除非我们已经完成了getDates 函数。
  • 我同意你上面的代码:) 我刚刚和提问者谈过
猜你喜欢
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
相关资源
最近更新 更多