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

169
Visualizações
Receiving returns from asynchronous functions

I've searched through multiple questions, but I have failed to find one that matches my case.

The following is the simplified version of my code:

function one() {
  let a;
  // does some fetching; takes about 1s
  a = 1; // value is obtained from above line
  return a;
}

function two() {
  let b;
  // does some fetching; takes about 2s
  b = 2; // value is obtained from above line
  return b;
}

function three() {
  let c;
  // does some fetching; takes about 0.5s
  c = 3; // value is obtained from above line
  return c;
}

var variables = [];

function final() {
  variables.push(one());
  variables.push(two());
  variables.push(three());
}
final();

console.log(variables);

What above code gives is [], while the desired output is [1, 2, 3](the order doesn't matter).

I've recognized that the solution is deeply related to async/await and promises(return new Promise(...)), but the implementation mostly fails, either because the await keyword does nothing, or promise comes out <pending>.

Also, through several experiments I've found that the return keyword also runs asynchronously, which means that one(), two() and three() almost certainly returns undefined.

Is there a way to get the return values in a synchronous manner?

Edit 1: The original code works as follows: (1)three different functions fetches json from different APIs which takes some seconds, (2) each functions returns the parsed data from the json, then (3) let the returned value be pushed onto var variables = []; array. I should have added this text in the first place.

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