array returns length of 0 although it has values

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 15:21:43

问题


so i am trying to push items to an array and it appears to be return a length of 0 although there are items in the array.

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)
.
.
}

my console.log is printing calendarDates and length : array

console log for length

the console.log lives in a seperate function

so why is it returning 0 for the length? when trying to console log a forEach loop nothing returns either so i dont thing its the browser showing the wrong value for fun


回答1:


This will help

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();



回答2:


getDates is async function. So, if you call:

getDates()
createCalendar(date, side)

createCalendar may be called before getDates() do successful. Async, Promise are really important, you should practice and study carefully about them.



来源:https://stackoverflow.com/questions/54877623/array-returns-length-of-0-although-it-has-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!