0

I want to display the variable dist in order as I iterate through the array. However the variable is not printing in order as I iterate. The for loop in the callback function seems to be executing in order but the first for loop is printing out of order. How do I make the first for loop execute in order

async function getStations(pBounds){
    
    let gasMarkers = []
    var currTankSize = 0
    if (CurrentSize === "TFive"){
      currTankSize = TankSize*.25
      console.log("currTSIZE: " + currTankSize)
    } 
    else if(CurrentSize === "Fifty"){
      currTankSize = TankSize *.5
      console.log("currTSIZE: " + currTankSize)
    }
    else if(CurrentSize === "SFive"){
      currTankSize = TankSize*.75
      console.log("currTSIZE: " + currTankSize)
    }
    else{ currTankSize = TankSize
      console.log("currTSIZE: " + currTankSize)}
    distCoords.push([waypoints[0][0], waypoints[0][1]])
    var distTrack = 0
    
    const service = new google.maps.places.PlacesService(map)
    const searchPromises = [];
    for (let i = 0; i < waypoints.length; i+=40){
      service.nearbySearch({
        location:{ lat: waypoints[i][0], lng:waypoints[i][1]},
        radius: '20000',
        type: ['gas_station']
      },callback)

    
    
      console.log("i before the second for loop: " + i)

      async function callback(results, status){
        if(status === google.maps.places.PlacesServiceStatus.OK){
          for (var j = 0; j < results.length; j++){
            if(google.maps.geometry.poly.containsLocation(results[j].geometry.location,pBounds) === true){
              //console.log("GEO: " + results[j].geometry.location.lat())
              
              let dist = await distanceCalc(distCoords[distTrack][0], distCoords[distTrack][1], results[j].geometry.location.lat(), results[j].geometry.location.lng() )
              dist = dist / Mpg
              currTankSize = currTankSize - dist
              var gasLvl = currTankSize/TankSize
              console.log("i: " + i + " j: " + j+ " Gas: " + gasLvl)
              
              //console.log("LEVEL: " + gasLvl)
              gasLvl = Math.round(gasLvl *10) / 10
              //console.log(results[j]['vicinity'])
              //console.log(results[j]['plus_code']['compound_code'])
              if (gasLvl <= .5){
                distCoords.push([results[j].geometry.location.lat(), results[j].geometry.location.lng()])
                distTrack+=1
                currTankSize = TankSize
                gasMarkers.push(new google.maps.Marker({
                  position: results[j].geometry.location, map, 
                  title: results[j]['name']
                }))

                if(!setGas.has(results[j]['vicinity'])){
                  var price = getGasStationInfo(results[j].geometry.location.lat(), results[j].geometry.location.lng())
                }

                var info = {
                  name: results[j]['name'],
                  vicinity: results[j]['vicinity'],
                  price: await price
                }
                if(!setGas.has(results[j]['vicinity'])){
                  GasInformation.push(info);
                  setGas.add(results[j]['vicinity'])
                  console.log("INLOOP:" + GasInformation);
                  GasSet = Array.from(new Set(GasInformation))
                  setValueArray(GasSet)
                }
                
                
                
              }
            }
          }
        }
      }
    }
    setGasMarkerArray(gasMarkers)
    
    //getGasStationInfo()
    //console.log("ARRAY: " + GasInformation )
    //console.log("SET" + ValueArray);
    //console.log("Value in the array: "+ValueArray.length);
    
  }
async function distanceCalc(lat1, long1, lat2, long2){
    const pt1 = {lat: lat1, lng: long1}
    const pt2 = {lat: lat2, lng: long2}

    let distanceService = new google.maps.DirectionsService()
    const dist = await Promise.resolve(distanceService.route({
      origin: pt1,
      destination: pt2, 
      travelMode: google.maps.TravelMode.DRIVING}))
    
    var miles = dist.routes[0].legs[0].distance.value

    miles = miles/1609.34
    //console.log("MILES: " + miles)
    return miles


  }

Console Example Output:

console output example

So far I tried making the function that contains the 2 for loops, async but that didn't work.

Mark
  • 1
  • 1
  • Hi Mark, could you add the closing brackets to your code as well, just for readability purposes. Currently you're calling each `service.nearbySearch` in parallel, so they'll all try to finish first. Does `service.nearbySearch` return a Promise as an alternative to a callback? – Emiel Zuurbier May 02 '23 at 07:50
  • What is `nearbySearch`? Make a promise from it that you can `await` in the loop, instead of having to pass a callback – Bergi May 02 '23 at 09:27
  • How would i implement a promise with nearbySearch? I also updated the code to show the whole function – Mark May 04 '23 at 21:02
  • See [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/1048572) – Bergi May 04 '23 at 21:03

0 Answers0