Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda