简体   繁体   English

在 for 循环中处理多个异步调用

[英]Handling multiple async calls inside for loop

I have a javascript for loop where I call a function for each lat-lng bound, inside this function I execute THREE async calls to google maps Places API, after all three calls execute I color the bounds green.我有一个 javascript for 循环,其中我为每个 lat-lng 边界调用 function,在这个 function 中,我对 google maps Places API 执行三个异步调用,在执行所有三个调用后,我将边界着色为绿色。

Issue is my for loop executes in a sync way and all bounds are colored green in a single tick instead of aiting for all three async calls to resume.问题是我的 for 循环以同步方式执行,并且所有边界都在一个勾号中显示为绿色,而不是等待所有三个异步调用恢复。

How can I do it so the for loop waits for the async calls to execute before going to the next iteration?我该怎么做才能让 for 循环在进入下一次迭代之前等待异步调用执行?

My code:我的代码:

async startScrapingGridLoop()
    {
        const self = this;

        for (var i = 0; i < self.zoneBoundaries.length; i++)
        {
            //Multiple async calls
            await self.scrapeCellWithPlaces(self.zoneBoundaries[i]);
            //After all three async calls end I want to color the bound green
            let currentPolygon = self.polygonsArray[i];
            currentPolygon.setOptions({fillColor: 'green', fillOpacity:0.6});

        }
    },

async scrapeCellWithPlaces(zoneBoundaries)
    {
        const self = this;
        var request = {};
        var bounds = new google.maps.LatLngBounds(new google.maps.LatLng({ lat:zoneBoundaries.sw.lat(), lng:zoneBoundaries.sw.lng() }), new google.maps.LatLng({ lat:zoneBoundaries.ne.lat(), lng:zoneBoundaries.ne.lng() }));


        for (var i = 0; i < self.types.length; i++)
        {
                
                
            request = { bounds: bounds, type: self.types[i] };
                
            self.placesService.nearbySearch(request, self.scrapeCellWithPlacesCallback);
            console.log('Scraping bounds for '+self.types[i]);
        }

    },

scrapeCellWithPlacesCallback(results, status, pagination)
    {
        const self = this;
         
        if (status == google.maps.places.PlacesServiceStatus.OK)
        {      
            for (var i = 0; i < results.length; i++)
            {
                self.results.push(results[i]);
            } 

            //self.setPlacesMarker(self.results);
            //self.fitPlacesBounds(self.results);
            
            if (pagination.hasNextPage)
            {
                console.log('fetching next set of sets');
                sleep:3;
                pagination.nextPage();

                for (var i = 0; i < results.length; i++)
                {
                    self.results.push(result[i]);
                } 
            }
        }
        console.log(self.results);
    },

You should transform the callback version of nearbySearch to promise version, so await on Promise would work您应该将 nearbySearch 的回调版本转换为 promise 版本,这样 await on Promise 就可以了

async startScrapingGridLoop() {
  const self = this

  for (var i = 0; i < self.zoneBoundaries.length; i++) {
    //Multiple async calls
    await self.scrapeCellWithPlaces(self.zoneBoundaries[i])
    //After all three async calls end I want to color the bound green
    let currentPolygon = self.polygonsArray[i]
    currentPolygon.setOptions({ fillColor: "green", fillOpacity: 0.6 })
  }
},

async scrapeCellWithPlaces(zoneBoundaries) {
  const self = this
  var request = {}
  var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng({
      lat: zoneBoundaries.sw.lat(),
      lng: zoneBoundaries.sw.lng(),
    }),
    new google.maps.LatLng({
      lat: zoneBoundaries.ne.lat(),
      lng: zoneBoundaries.ne.lng(),
    })
  )

  for (var i = 0; i < self.types.length; i++) {
    request = { bounds: bounds, type: self.types[i] }

    await self.nearbySearchPromise(request);
    console.log("Scraping bounds for " + self.types[i])
  }
},

nearbySearchPromise(request) {
  const self = this

  return new Promise((resolve) => {
    self.placesService.nearbySearch(request, (results, status, pagination) => {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          self.results.push(results[i])
        }
    
        //self.setPlacesMarker(self.results);
        //self.fitPlacesBounds(self.results);
    
        if (pagination.hasNextPage) {
          console.log("fetching next set of sets")
          sleep: 3
          pagination.nextPage()
    
          for (var i = 0; i < results.length; i++) {
            self.results.push(result[i])
          }
        }
      }
      console.log(self.results)

      resolve()
    })
  })
}

You could try to fetch all the data you need before you process it, using Promise.all .您可以尝试使用Promise.all在处理之前获取所需的所有数据。

Eg.:例如。:

async function scrapeGrid() {
  let boundaries = [];
  this.zoneBoundaries.forEach(boundary => boundaries.push(scrapeCellWithPlaces(boundary)));
  const polygons = await Promise.all(boundaries);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM