DEV Community

Touhidul Shawan
Touhidul Shawan

Posted on

Need help

I am creating a helper function to get weather data using open-weather api

require("dotenv").config();
import axios from "axios";

export const getWeatherData = async (cityName: any) => {
  let getData = {};
  try {
    const response = await axios.get(
      `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${process.env.WEATHER_API_KEY}&units=metric`
    );
    const data = await response.data;
    getData = {
      forecast: data.weather[0].description,
      cityName: data.name,
      coordinate: data.coord,
    };
    return getData;
  } catch (err) {
    // console.log("Something Wrong!! Try again later.");
    console.log(err);
  }
};
Enter fullscreen mode Exit fullscreen mode

This function receives a cityName. now I am calling this function on another file to get data

app.get("/weather", (req, res) => {
  if (!req.query.location) {
    return res.send({
      error: "You must give an address",
    });
  }
  const data = getWeatherData(req.query.location);
});
Enter fullscreen mode Exit fullscreen mode

Here in data variable is showing that it is promise rather than object that I return from getWeatherData function.

How can I get the object that I want to get from getWeatherData?

Oldest comments (2)

Collapse
 
saraogipraveen profile image
Praveen Saraogi

Yes, since getWeatherData() is a promise you need to await for it or use then to get data out of it.
For eg:

app.get("/weather", async (req, res) => {
  if (!req.query.location) {
    return res.send({
      error: "You must give an address",
    });
  }
  const data = await getWeatherData(req.query.location);
});
Enter fullscreen mode Exit fullscreen mode

OR

app.get("/weather",  (req, res) => {
  if (!req.query.location) {
    return res.send({
      error: "You must give an address",
    });
  }
  getWeatherData(req.query.location).then(response => {
     const data = response; 
  });
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
touhidulshawan profile image
Touhidul Shawan

I tried this. But there was slight mistake in my code. Thank you♥️