Need help
Touhidul Shawan

Touhidul Shawan @touhidulshawan

About: Hello World!

Location:
404
Joined:
Jan 19, 2020

Need help

Publish Date: May 19 '21
0 2

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?

Comments 2 total

  • Praveen Saraogi
    Praveen SaraogiMay 19, 2021

    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
    • Touhidul Shawan
      Touhidul ShawanMay 19, 2021

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

Add comment