Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Returning a value in a function after a promise results in undefined

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!