为什么 .find() 如果它适用于全局变量,则不起作用



我有这个代码:

/**
     * 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"," ...

问题只出在 chrome canary 中 - 所以它看起来像 chrome canary bug。不知道为什么,但是重新启动后相同的代码起作用了。这很可能是内存泄漏。当现在一切再次正常工作时,我无法提供任何有用的测试。

最新更新