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);
}
};
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);
});
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?
Top comments (2)
Yes, since getWeatherData() is a promise you need to
await
for it or usethen
to get data out of it.For eg:
OR
I tried this. But there was slight mistake in my code. Thank you♥️