繁体   English   中英

为什么我没有为这个变量定义?

[英]Why am i getting undefined for this variable?

我有这个变量test1 = [] ,我向它推送了一些res.json 我希望它是这样的[[{json,json}]] ,但当我尝试像test1[0]那样迭代它时,它给了我 undefined 。 有人可以向我解释test1[0]是如何未定义的吗? 我怎样才能从中获得价值?

下面是这个变量的 chrome 控制台 output。 在此处输入图像描述

片段:test1 = data_array

var data_array = []
const BookingHistory = getBookings(userDbID).then((json) => {data_array.push(json)})

console.log("test1", data_array[0]) //undefined

获取预订:

export const getBookings = (userDbId) => {
    const id = userDbId; //one of the global state that is sent to Date from App
  
    // Create our request constructor with all the parameters we need
    const request = new Request(`/users/${id}/bookings`)

    return fetch(request)
        .then((res) => {
        if (res.status === 200) {
          return res.json();
        }
        })
        .then((json) => {return json})
      .catch((error) => {
        console.log(error);
      });
}

fetch() function 是异步的。 它返回Promise ,这意味着不会立即评估其返回值。 如果要使用它的返回值,则必须在处理程序 function 中进行(或者使用async/await语法)。 你可以像这样修改你的代码:

let data_array = []
const BookingHistory = getBookings(userDbID).then((json) => {
  // This only runs after response from fetch request arrives. Not immediately
  data_array.push(json);
  console.log(data_array[0]);  // Correct value this time, data_array is no longer an empty array
  ... // The rest of the code that makes use of the updated value of data_array variable
})

console.log("test1", data_array) // This evaluates data_array immediately so, at this point, data_array is still an empty array

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM