-2

I'm having promise getting a value from a promise. The promise is supposed to return 123. But X is a promise.

const promise1 = Promise.resolve(123);
const X = promise1.then((v) => { return (v) })
const X = async () => await promise1.then((v) => { return (v) })

I've checked online example, they mostly do a console.log inside then which shows that the value is there but when I return it inside then, it will give me a promise.

I've also read that the promise will result in a promise which is happening here.

So how can I get the value back ?

Thanks !!!

Update:

My program is not async. I've also tried

const X = await promise1

which was suggested in a comment. I get a red line below it. So I've tried

const X = async () => await promise1

and I still get a promise.

EBDS
  • 1,244
  • 5
  • 16
  • 1
    of course, there is `const X = await promise1` to get the value of a promise (this only works inside an async function, or top level of modules – Jaromanda X Aug 27 '23 at 10:08
  • @JaromandaX Thanks. I've updated the question. My program is not async. So it will complain when I use await. I've tried to create an async function to await it. I still get a promise. – EBDS Aug 27 '23 at 10:15
  • 1
    `I still get a promise` because that's what async functions return by definition . – Jaromanda X Aug 27 '23 at 10:18
  • 2
    `I get a red line below it.` because you're not in an async function or at a top level in a module - there is no way around this limitation, as asynchronous results can not be "retrieved" synchronously – Jaromanda X Aug 27 '23 at 10:19
  • 1
    You cannot get the value of a promise without `then` or `await`. Wrapping it in more promises or async functions will not change that, it just adds more layers of promises. – deceze Aug 27 '23 at 10:24

0 Answers0