Javascript 数组返回长度0,尽管它有值

Javascript 数组返回长度0,尽管它有值,javascript,async-await,Javascript,Async Await,因此,我尝试将项推送到数组中,虽然数组中有项,但返回的长度似乎为0 let calendarDates = [] async function getDates() { const response = await fetch('/calendars/fetch_dates') let res = await response.json() res.forEach(el => { calendarDates.push(el) }) } g

因此,我尝试将项推送到数组中,虽然数组中有项,但返回的长度似乎为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)
.
.
}
my console.log正在打印日历日期和长度:

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

那么,为什么长度返回0呢? 当尝试控制台记录forEach循环时,也不会返回任何结果,因此我不认为浏览器显示了错误的值是为了好玩

这会有所帮助

异步函数Main(){ 让日历日期=[]
calendarDates=等待getDates(); 创建日历(日期,侧面) } 异步函数getDates(){ const response=wait fetch(“/calendars/fetch\u dates”) return wait response.json(); } 函数createCalendar(日期,侧面){ log('createCalendar',calendarDates,“是数组吗?”,array.isArray(calendarDates),'length',calendarDates.length); }
Main()
getDates
是异步函数。因此,如果你打电话:

getDates()
createCalendar(date, side)

在getDates()成功执行之前,可能会调用
createCalendar
。异步、承诺非常重要,您应该仔细练习和学习它们

您将
控制台.log
放在哪里?@YongQuan更新了我的代码片段,以显示控制台日志livesgetDates是一个异步函数,而createCalendar是一个同步函数。因此,将首先调用createCalendar,并在getDates函数获取异步数据之前尝试读取数组的长度。我相信您看到的不一致之处在于
console.log()
的工作方式(至少在Chrome中)
createCalendar()
getDates
完成之前被调用,但是
console.log()
被延迟,并使用一个更晚的值
calendarDates
。。。我不知道我的解释是否正确。。类似于
console.log
计算参数,但由于calendarDates是一个数组,所以它是通过引用传递的。因此,您不能相信日志中的值与实际调用时的值相同;创建日历(日期、侧面);我们已经为
getDates
函数使用了
wait
,因此除非我们完成了
getDates
函数,否则不会调用
createCalendar
函数。我同意你上面的代码:)我刚刚和提问者谈过