0

I'm playing around with Promises, but I cannot figure out how to get back the value as a result of it work? So, in promise .then stage it gives me the right result, but outside it's showed as Promise <pending>. What I forgot?

Thank you.

P.S. Please, do not block my question, I saw tens of similar this one, but it does not help me

const computeResult = () => {
  return 2
}

const randomizer = () => {
  const delay = 1000

  return new Promise(r => setTimeout(r, delay)).then(() => computeResult());
}

  const randomID = randomizer()
    .then(res => {
      console.log(res, 'res') // return what expected - '2'

      return res
    })
    .catch(e => console.log(e.message))

  console.log(randomID, 'randomID') // return always Promise <pending>
Max Travis
  • 1,228
  • 4
  • 18
  • 41
  • 2
    You have you call `.then` in any consumer of a `Promise` in order to access the value it resolves to. – CertainPerformance Aug 28 '18 at 06:58
  • Where is asyncFunc? Should it be randomizer().then(...) – Radonirina Maminiaina Aug 28 '18 at 06:59
  • @RadonirinaMaminiaina yes, it's my typo just. You are right – Max Travis Aug 28 '18 at 07:00
  • @CertainPerformance I have already `.then` in my promise, where I gets the value, but not outside it. I also saw you proposed post, but it does not help! Why you block me? – Max Travis Aug 28 '18 at 07:02
  • `randomID` is a `Promise`, so you must call `.then` on it in order to access the value it resolves to. Please read the linked canonical. – CertainPerformance Aug 28 '18 at 07:04
  • @CertainPerformance and... I still cannot get the value outside the promise once it finish own work – Max Travis Aug 28 '18 at 07:08
  • You don't understand. You have to move ALL YOUR CODE inside the `.then()`. The `then` IS THE OUTSIDE. There is one other alternative, move your entire app inside an async function and then use await: `async function main () { /* ALL YOUR CODE */ }; main().then(console.log('exiting.. bye!'))` – slebetman Aug 28 '18 at 07:22
  • Read my answer to this question: https://stackoverflow.com/questions/17460556/undefined-return-value-from-the-function-call-javascritpt/17460802#17460802. It's about callbacks but it also applies to promises because as you have just discovered, promises are just a design pattern around callbacks - they don't let you escape from callbacks – slebetman Aug 28 '18 at 07:24
  • @MaxTravis You always have to *wait* for the promise. You cannot access the future value immediately. – Bergi Aug 28 '18 at 08:09

0 Answers0