为什么.find()在全局变量上工作时不起作用?

问题描述 投票:0回答:1

我有这个代码:

/**
     * 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"," ...
javascript arrays
1个回答
0
投票

问题只出现在铬金丝雀上 - 所以它看起来像铬金丝雀虫。不知道为什么,但重启后相同的代码工作。它可能是内存泄漏。当现在所有工作再次起作用后,我无法提供任何有用的测试。

© www.soinside.com 2019 - 2024. All rights reserved.