【问题标题】:Returing positions using axios使用 axios 返回位置
【发布时间】:2021-12-31 14:23:28
【问题描述】:

我正在尝试遍历对象数组并使用对象的值调用我的 API。然后登录控制台。我的 API 正在返回所需的值,但输出是这样的: [ Promise { <pending> }, Promise { <pending> } ]

我的功能:

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));

【问题讨论】:

    标签: javascript node.js asynchronous axios


    【解决方案1】:

    您正在向 API 发出多次调用,从而创建了多个 Promise。您在控制台中看到的是这些承诺对象的数组。您需要编写如下代码来等待它们全部完成。

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

    【讨论】:

      【解决方案2】:
      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 = Promise.all(
          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));
      

      Promise.All() 确保所有同步代码的数组都成功执行,并返回一个解析为结果数组的 Promise。

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 2017-09-07
      • 2017-06-09
      • 1970-01-01
      • 2019-08-03
      • 2018-01-12
      • 2016-12-27
      相关资源
      最近更新 更多