Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda