Blink Rankin
Blink Rankin

Reputation: 233

array returns length of 0 although it has values

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

Upvotes: 1

Views: 266

Answers (2)

Vu Luu
Vu Luu

Reputation: 790

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.

Upvotes: 1

Kuldeep Bhimte
Kuldeep Bhimte

Reputation: 959

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

Upvotes: 1

Related Questions