【问题标题】:how to get axios to return the object instead of promise如何让axios返回对象而不是promise
【发布时间】:2021-05-18 17:03:04
【问题描述】:

目前,我的代码正在返回一个承诺,我需要它来返回它从 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;

【问题讨论】:

标签: javascript reactjs axios weather-api


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 2020-10-06
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多