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