0

When I try to capture the value of a Promise in an array outside of .then(), the array is populated with undefined (though console.log() logs the correct values).

  async function fetchCoordinates(pluscode) {
    let response = await fetch(url);
    return await response.json();
  }

  let places = []
  fetchCoordinates(pluscode)
  .then(geoinfo => {
    console.log(geoinfo)
    console.log(geoinfo.plus_code.geometry.location.lat)
    places.push(
      {position: new google.maps.LatLng(
        geoinfo.plus_code.geometry.location.lat, 
        geoinfo.plus_code.geometry.location.lng
      )}
    )
  })
Edgar Derby
  • 2,543
  • 4
  • 29
  • 48
  • tldr; do your work with `places` inside the `then`, or use another async function – coagmano Nov 09 '21 at 07:40
  • is places undefined within the `.then()` as well after pushing the object? – DragonInTraining Nov 09 '21 at 07:40
  • The code shown should work just fine, provided you understand that `places` will only have the new information once the asynchronous calls are complete. (Side note: Your `fetchCoordinates` code is being hit by the `fetch` API footgun I write about [here](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). You have to check `response.ok`.) – T.J. Crowder Nov 09 '21 at 07:42

0 Answers0