繁体   English   中英

如何让 axios 返回 object 而不是 promise

[英]how to get axios to return the object instead of promise

目前,我的代码正在返回 promise 我需要它返回从 API 调用获得的 object,该怎么做?

import axios from 'axios';

const baseUrl = 'http://api.openweathermap.org/data/2.5/weather?';

const getWeatherData = async (city,country) => {
    // const result=await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`)
    // return result;
    
    axios({
        method: "GET",
        url: `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`,
      })
        .then((response) => {
          return response.data;
      
        })
        .catch((error) => {
          console.log(error);
        });
}

export default getWeatherData;
try {
  const response = await axios({
    method: "GET",
    url: `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`,
  });
  return response.data;
} catch (err) {
  console.error(err);
}

您可以通过这种方式重写您的 axios 调用,因为您的 function 被标记为异步。

异步函数总是返回承诺。 在异步函数中,您可以在其他异步函数或返回承诺的函数之前使用await

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM