0

How can I assign the resulting content from a promise function to a variable?

I can see the result of a function in a var.then but what I really want to do is assign that result to a variable that I use elsewhere. I want to avoid lots of nested get thing a -> .then do thingb -> .then do thing c

I've created a simple reproduction, but my real case is getting data from the result fetch

I have a script that calls a function in a lib (see Simple library at the end of this post) below that returns Promise<string>.

I can use the function access the result inside a .then by doing

const myLib = new MyLib()
const hello = myLib.hello()
hello.then((result) => {
    console.log(`Result : ${result}`)
})

What I want to do though is assign the value of this result to a variable for use elsewhere.

hello at this point is an object Promise when logged.

How do I get the value and assign it to a var?

Things I've tried and what they result in

Return the result from .then - returns a Promise

var stringy = hello.then((result) => {
    return result
})

Stringy: [object Promise]

Declare a variable and assign it within .then - Undefined output

var stringy
hello.then((result) => {
    stringy = result
})

Stringy: undefined

Use await

const hello = await myLib.hello()

Top-level 'await' expressions are only allowed when the 'module' option is set to 
'es2022', 'esnext', 'system', 'node16', or 'nodenext', 
and the 'target' option is set to 'es2017' or higher.ts(1378)

Simple library

class MyLib {
    public async hello(): Promise<string> {
        return 'Hello World!';
    }
}

export default MyLib
Anonymouslemming
  • 518
  • 2
  • 9
  • 16
  • 1
    This is an XY problem. You probably should not have a global shared mutable variable. What are you trying to achieve? top-level await may be a solution if you use ES modules as the error is telling you, but there is nothing wrong with having a main function that is async. Your code does not need to be "flat", if stuff happens in the future, then so be it. – geoffrey Aug 02 '23 at 16:58
  • 1
    Forgot to mention that Promise.then behaves like Array.flatMap, so you would not be nesting even if the return value of a callback is a Promise itself, it would get flattened automagically. – geoffrey Aug 02 '23 at 17:04
  • You cannot access it elsewhere, *without waiting for the promise*. It's just impossible to get a value that doesn't exist yet from the future. It seems you already know how to wait for promises, use that syntax. "*I want to avoid lots of nested get thing a -> .then do thingb -> .then do thing c*" - using `await` means you don't need to nest. If you have trouble with applying this, please post your real code instead of a toy example. – Bergi Aug 02 '23 at 19:16

0 Answers0