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

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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