I am coming from a Python background and now learning JavaScript, I think I have some concepts confused regarding returning values after a promise is resolved. I have a simple script which collects weather data from OpenWeatherMap using Axios.
Given the following function, using console.log() gives me the correct output:
const axios = require('axios');
const apiKey = process.env.OPEN_WEATHER_MAP_API_KEY;
let getWeather = (zip) => {
const url = `https://api.openweathermap.org/data/2.5/weather?zip=${zip},au&units=metric&appid=${apiKey}`;
axios.get(url)
.then((resp) => {
const name = resp.data.name;
const temp = parseFloat(resp.data.main.temp.toFixed(1));
console.log(`The weather in ${name} is ${temp} degrees`);
});
};
getWeather('2000');
Running the code returns The weather in Sydney South is 21 degrees.
However if I modify the code so that the string after the promise is returned instead of console.log(), I get undefined:
const axios = require('axios');
const apiKey = process.env.OPEN_WEATHER_MAP_API_KEY;
let getWeather = (zip) => {
const url = `https://api.openweathermap.org/data/2.5/weather?zip=${zip},au&units=metric&appid=${apiKey}`;
axios.get(url)
.then((resp) => {
const name = resp.data.name;
const temp = parseFloat(resp.data.main.temp.toFixed(1));
return `The weather in ${name} is ${temp} degrees`;
});
};
myWeather = getWeather('2000');
console.log(myWeather);
Running the code returns undefined.
Can someone point me in the right direction of what went wrong?