如何让axios返回对象而不是promise

问题描述

目前,我的代码正在返回一个承诺,我需要它返回它从 API 调用获取的对象,该怎么做?

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 调用,因为您的函数被标记为异步。

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