0

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

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

这是我尝试过的代码,控制台日志返回数组 WITH distance 但是当我在 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方法解决了结果,也许这是导致问题的原因?

4

1 回答 1

1

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

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

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

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;
}

这是“现成的”写的,所以不能说它会按原样运行,但应该给出一个想法。

于 2019-03-27T22:39:27.893 回答