首先要说明我要达到的目标。我从数据库中获取餐馆,然后添加到用户位置和餐馆位置的计算距离。我将其作为属性添加到餐厅对象的位置。然后,我想根据从附近到远处的距离对结果进行排序。
但是诺言结果(带有距离的餐厅)不包含距离。
这是我尝试过的代码,控制台日志返回带有距离的数组,但是当我在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
方法解决了这个问题,也许是引起问题的原因吗?
答案 0 :(得分:1)
因此,我认为您遇到的主要问题是在resolve(restaurants)
循环内调用restaurants.map
。这意味着在循环的第一次迭代中,您将解决承诺。现在,如果您的循环足够小,并且每次迭代的处理时间都足够小,您可能不会真正注意到它,因为循环将继续进行,并且事情将被填充,但是任何“时间点”调查(例如断点)将显示您所看到的内容-并非所有餐厅都已处理完毕。
我认为还有其他一些事情可能也会有所帮助。不熟悉您在那里使用的API或您正在使用的环境,我不能百分百确定。使用this.locationService.getUserLocation
和this.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;
}
这是写在“现成的”上的,因此不能说它可以按原样运行,但应该给出一个想法。