我有这段代码:
/**
* Fetch all restaurants.
*/
static fetchRestaurants(callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', DBHelper.DATABASE_URL);
xhr.onload = () => {
if (xhr.status === 200) { // Got a success response from server!
const json = JSON.parse(xhr.responseText);
const restaurants = json.restaurants;
callback(null, restaurants);
} else { // Oops!. Got an error from server.
const error = (`Request failed. Returned status of ${xhr.status}`);
callback(error, null);
}
};
xhr.send();
}
/**
* Fetch a restaurant by its ID.
*/
static fetchRestaurantById(id, callback) {
// fetch all restaurants with proper error handling.
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
callback(error, null);
} else {
console.log(restaurants); //restaurants exists
const restaurant = restaurants.find(r => r.id === 1);
console.log(restaurant); //restaurant is undefined
window.teszt = restaurants; //for tests
if (restaurant) { // Got the restaurant
callback(null, restaurant);
} else { // Restaurant does not exist in the database
callback('Restaurant does not exist', null);
}
}
});
}
当我在teszt上运行相同的.find(r => r.id === 1)
时,它可以工作。如果我在数组const restaurant = restaurants[id-1]
中只抓取所需的项并且它未被定义,那么代码也可以工作。但我真的更喜欢.find,以防json结构发生变化。
这是restaurants.json的一部分,这与餐馆变量https://pastebin.com/tVLyUTVH
相同退出JSON.stringify(restaurants)
似乎也很正常。
[{"id":1,"name":"Mission Chinese Food","neighborhood":"Manhattan","photograph":"1.jpg"," ...
答案 0 :(得分:0)
问题只出现在铬金丝雀上 - 所以它看起来像铬金丝雀虫。不知道为什么,但重启后相同的代码工作。它可能是内存泄漏。如果之后所有工作再次起作用,我无法提供任何有用的测试。