Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returing positions using axios

I am trying to iterate through an array of objects and call my API using the value of the object. And then log in to the console. My API is returning the values needed, but the output is this:
[ Promise { <pending> }, Promise { <pending> } ]

My function:

async function geoEncode() {
  const clients = [
    {
      nome: "John",
      address: "Jardim Planalto Sinibaldo Cassino 33",
    },

    {
      nome: "Joseph",
      address: "R. Afrizia Martins Sanacato - Jardim Natalia",
    },
  ];
  const baseUrl = "https://api.tomtom.com";
  const endPoint = "search/2/geocode";
  const format = ".json";
  const apiKey = "Hq2eTTQvtJRna5MMAsAsARlsQCxv5XjR";
  const clientsPositions = clients.map(async (client) => {
    const address = client.address;
    const position = await axios
      .get(`${baseUrl}/${endPoint}/${address}${format}/?key=${apiKey}&limit=1`)
      .then((response) => response.data.results[0].position)
      .catch((error) => error.detailedMessage);
    return position;
  });
  return clientsPositions;
}

geoEncode().then((result) => console.log(result));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are issuing multiple calls to the API and thus creating multiple promises. What you are seeing in the console is an array of those promise objects. You need to write code like below to wait for all of them to complete.

...
Promise.all(geoEncode()).then((values) => {
  console.log(values);
});
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading