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

128
Visualizações
JavaScript - Can't return value from function with promise

I am learning promise in JavaScript but I don't understand why my function doesn't return the right value.

This is my function:

function promise() {
  let p = new Promise((resolve, reject) => {
    return resolve(["a", "random", "array"]);
  });

  p.then((response) => {
    return response;
  }).catch((error) => {
    return error;
  });
}

console.log(promise());

If I run the code I get undefined.

I think the problem is that the console.log is executed before the value of the .then is returned.

Can somebody please help me to solve this problem and maybe explain the problem? :)

Thanks for every answer.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Two things:

  1. You must return the promise p from within the promise function.

  2. You must await the result of the promise returned by the function before you can access its fulfilled value:

function promise() {
  let p = new Promise((resolve, reject) => {
    return resolve(["a", "random", "array"]);
  });

  p.then((response) => {
    return response;
  }).catch((error) => {
    return error;
  });
  
  // 1. Return the promise from the function:
  return p;
}

// 2. Await the result before using it:
promise().then((result) => {
  console.log(result);
});

You said you're learning about promises. Async/await makes all of this much easier:

<script type="module">
// Top level await is available in ES modules

async function promise () {
  try {
    return ["a", "random", "array"];
  }
  catch (exception) {
    return exception;
  }
}

const result = await promise();
console.log(result);

</script>

about 4 years ago · Juan Pablo Isaza 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