Promises question

I have the following code:

function geocode(location) {
  geocoder = new google.maps.Geocoder();

  if (!location) {
    console.error("Location argument is null.");
    return;
  }

  return new Promise((resolve, reject) => {
    geocoder.geocode({ address: location })
      .then((result) => {
        const { results } = result;

        if (results) {
          const coordinates = results[0].geometry.location;
          const lat = coordinates.lat(); // These are functions
          const lng = coordinates.lng();

          resolve({ lat: lat, lng: lng });
        }
      })
      .catch((error) => {
        console.error("Geocode was not successful: " + error);
        reject(error);
      });
  });
}


This geocode() function is from the Google Maps API. I'm calling it here:

// Create new markers
locations.forEach(async (location) => {
  const coordinates = await geocode(location);

  if (coordinates) {
    const marker = new AdvancedMarkerElement({
      map: map,
      position: coordinates,
      title: "Uluru",
    });
  }
});


My question is, do I really need to wrap the geocode function in a Promise constructor? Admittedly, I got this answer from chatGPT after having difficulties with calling the data from geocode func inside the forEach. Whenever I tried to make a new marker, it wouldn't wait for the geocode func to return. My understanding of Promises is really limited -- but I did try to use the
await
syntax on the geocoder.geocode() line but my IDE complained that 'await' has no effect on the type of this expression -- so I'm assuming the way it's set up in the Google library doesn't allow you to use
await
?
Was this page helpful?