我有这个变量test1 = []
,我向其中推了res.json
。
我希望它像这样的[[{json,json}]]
,但是事实证明,当我尝试像这样的test1[0]
进行迭代时,它给我带来了不确定的感觉。
有人可以向我解释test1[0]
的定义如何吗?以及如何从中获取价值?
片段: test1 = data_array
var data_array = []
const BookingHistory = getBookings(userDbID).then((json) => {data_array.push(json)})
console.log("test1", data_array[0]) //undefined
getBookings:
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);
});
}
答案 0 :(得分:1)
fetch()
函数是异步的。它返回一个Promise
,这意味着它的返回值不会立即求值。如果要使用其返回值,则必须在处理程序函数中使用它(或使用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