Google Places APIJavascriptを使用してレストランを検索したい長方形の境界の配列があります。
最初は、境界配列をfor
ループで繰り返すことを考えました。問題は、各反復で非同期API呼び出しを行い、for
ループが同期アクションであるということです。
理想的には、各API呼び出しの間に1分の違いがあるすべての境界を反復処理し、すべての境界が検索されたら終了します。おそらく、setInterval
それを回避することはできません。
これどうやってするの?
loopSearch(zoneBoundaries)
{
for (var i = 0; i <= zoneBoundaries.length; i++)
{
const self = this;
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(zoneBoundaries[i].sw),
new google.maps.LatLng(zoneBoundaries[i].ne)
);
self.placesService = new google.maps.places.PlacesService(self.map);
var request = { bounds: bounds, types: [ 'restaurant', 'bar'] };
self.placesService.search(request, self.placesCallback);
}
},
クリーンな解決策の1つは、Promise allを使用し、マップとともに待機して、ゾーン境界内の座標を反復処理することです。
await Promise.all(
zoneBoundaries.map(async (val, index) => {
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(zoneBoundaries[index].sw),
new google.maps.LatLng(zoneBoundaries[index].ne)
);
self.placesService = new google.maps.places.PlacesService(self.map);
var request = { bounds: bounds, types: [ 'restaurant', 'bar'] };
const response = await self.placesService.search(request, self.placesCallback);
const result = response.json()
console.log(result)
})
);
上記のアプローチを使用する利点はmap
、プロミスが返されるとすぐに次のアイテムに移動しPromise.all
、これらのプロミスがすべて解決されるまで待機することです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加