Promise解析数据不可访问

Promise resolved data is not accesable

首先想解释一下我想要实现的目标。我从数据库中获取餐厅,然后添加从用户位置和餐厅位置的计算距离。我将其作为 属性 添加到餐厅对象。然后我想根据从近到远的距离对我的结果进行排序。

但承诺结果(有距离的餐厅)不包含距离。

这是我尝试过的代码,控制台向我记录 returns 带距离的数组,但是当我在 chrome 调试器中设置断点时,我无法看到 属性.

这是承诺calculateDistance function:

 calculateDistance(restaurants: Array<Restaurant>): Promise<Array<Restaurant>> {
    const promise = new Promise<any>((resolve, reject) => {
        // const restaurantDistances = [];

        restaurants.map((restaurant) => {
            const restaurantLocation: LatLng = new LatLng({
                lat: restaurant['Restaurant']['Lat'],
                lng: restaurant['Restaurant']['Long']
            });

            this.locationService.getUserLocation().then(() => {
                this.googlemapService.initGoogleMapsApi().then(() => {
                    const distance = this.googlemapService.computeDistanceBetween(this.locationService.location, restaurantLocation);
                    restaurant['Restaurant']['Distance'] = distance;
                    // restaurantDistances.push(restaurant);
                    console.log(restaurants, 'restMap', restaurant, distance);
                    resolve(restaurants);
                });
            }).catch( error => {
                console.log('error = ', error);
            });
        });
    });
    return promise;
}

这是在成功函数中:

this.calculateDistance(restaurants).then((restaurantsDist) => {
  console.log('after Calc distance', restaurantsDist, restaurants);
  this.determinInstanceStorage(fetchMethodName, restaurantsDist, resolve);
});

谁能帮帮我,我用 map 方法解决了结果,也许这是导致问题的原因?

所以,我认为您 运行 遇到的主要问题是您在 restaurants.map 循环中调用 resolve(restaurants)。这意味着在循环的第一次迭代中,您将解决承诺。现在,如果您的循环足够小并且每次迭代的处理时间足够短,您可能不会真正注意到它,因为循环会继续并且事情会被填充,但是任何 "point in time" 调查(例如断点)将揭示您所看到的——并非所有餐厅都已处理。

我认为还有其他一些事情也可能有所帮助。不熟悉你在那里使用的 API 或你工作的环境,我不能 100% 确定。对于 this.locationService.getUserLocationthis.googleMmapService.initGoogleMapsApi,它们看起来像是只需要发生一次的操作(不是针对 restaurants 循环的每个实例)。你能把它们从 restaurants.map 循环中拉出来吗?

此外,将其更改为 async 函数可能会使其更易于阅读,因为您拥有 then 的多个级联。所以,最后,是这样的:

async function calculateDistance(restaurants: Array<Restaurant>): Promise<Array<Restaurant>> {
    await this.locationService.getUserLocation();
    await this.googlemapService.initGoogleMapsApi();
    restaurants.map((restaurant) => {
        const restaurantLocation: LatLng = new LatLng({
            lat: restaurant['Restaurant']['Lat'],
            lng: restaurant['Restaurant']['Long']
        });

        const distance = this.googlemapService.computeDistanceBetween(
            this.locationService.location, restaurantLocation
        );
        restaurant['Restaurant']['Distance'] = distance;
        // restaurantDistances.push(restaurant);
        console.log(restaurants, 'restMap', restaurant, distance);
    });
    return restaurants;
}

这是写成 "off-the-cuff" 所以不能说它会按原样运行,但应该给出一个想法。