简体   繁体   中英

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.

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.

How can I do it so the for loop waits for the async calls to execute before going to the next iteration?

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

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 .

Eg.:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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