Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!