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

434
Visualizações
How to return a variable from an async function?

I'm trying to learn async functions and am struggling to get the following to work.

async get_price(ticker) {
  var price = await axios
    .get(`https://marketwebsite.com/${ticker}`, {
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36",
      },
    })
    .then((res) => {
      const $ = cheerio.load(res.data);
      $(".todays_price").each((index, element) => {
        var value = $(element)
          .find(".current_price")
          .text()
          .replace(/\s\s+/g, "");
        return value;
        console.log(value); // THIS WORKS
      });
    })
    .catch((err) => console.error(err));
}

When i call

var price = get_price(symbol); 

I cannot get any return from this function. The console log noted above does work, however i cannot get the value to return from this function.

I have tried to await get_price(symbol) as well.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

there are two things:

first, the code in the then() block is returned to price variable that isn't returned

second, var price = get_price(symbol); the function call is not using await so if you log that you will get the promise instead of the value.

you need to return the axios call and await it when using the function elsewhere

over 4 years ago · Santiago Trujillo Relatório

0

There are a few issues in your snippet including:

  • You are not returning price from your get_price function
  • You are not returning anything in your .then() call

Try the following snippet:

async function get_price(ticker) {
  return await axios
    .get(`https://marketwebsite.com/${ticker}`)
    .then((res) => {
      const $ = cheerio.load(res.data);
      return $(".todays_price").map((index, element) => {
        var value = $(element)
          .find(".current_price")
          .text()
          .replace(/\s\s+/g, "");
        return value;
      });
    })
    .catch((err) => console.error(err));
}

get_price('ticker').then((res) => {
  console.log(res); // Should print array of the values
});

I've used the jQuery .map method as it seems like you intended to return the values for each element.

I suggest going through the documentation on async await and promises on the MDN docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

over 4 years ago · Santiago Trujillo Relatório
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