Javascript 如何在for循环中处理googlemapsapi调用

Javascript 如何在for循环中处理googlemapsapi调用,javascript,vue.js,Javascript,Vue.js,我有一个矩形边界数组,我想用Google Places API Javascript搜索餐厅 起初,我考虑使用for循环遍历边界数组。问题是,在每次迭代中,我将进行一个异步API调用,而的循环是一个同步动作 理想情况下,我希望迭代所有边界,每个API调用之间相差一分钟,并在搜索完所有边界后完成,可能使用setInterval,但我无法完全理解它 我该怎么做 loopSearch(zoneBoundaries) { for (var i = 0; i <= zoneB

我有一个矩形边界数组,我想用Google Places API Javascript搜索餐厅

起初,我考虑使用
for
循环遍历边界数组。问题是,在每次迭代中,我将进行一个异步API调用,而的
循环是一个同步动作

理想情况下,我希望迭代所有边界,每个API调用之间相差一分钟,并在搜索完所有边界后完成,可能使用
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);
        }
    },
loopSearch(ZoneBondaries)
{

对于(var i=0;i一个干净的解决方案是使用Promise all和Wait以及map来迭代区域边界内的坐标

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后立即转到下一项。所有
将等待所有这些承诺得到解决