简体   繁体   中英

how to get axios to return the object instead of promise

currently, my code is returning a promise I need it to return the object that It is getting from the API call, how would do that?

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

You can rewrite your axios call this way since your function is flagged as async.

async functions always return promises. Within async functions, you can use await infront of other async functions or functions that return promises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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