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?

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top 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♥️

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay