Returning a value from a promise

I am trying to return a value from a promise but whatever I try, I always end up returning a new promise :confused:

let query = URL
let result = Fetch.fetch(query)
    ->then(Fetch.Response.text)
    ->then(balance => resolve(Ok(balance->Belt.Float.fromString)))
    ->catch(err => reject(err))

(I am using bs-fetch)
I tried different combinations but result is always a promise when I want it to be result<float, string>. All the examples I could find online finish with ->ignore or return a promise.
How can I break the chain of promises and return the float value I get from calling the URL?
Thanks

That is not possible by design. Once a value is inside a promise, it can’t be extracted.

(Some may say there are tricks to do it, but they are just that–hacky workarounds that will quickly break your application.)

Fortunately, it’s almost always possible to use the promise itself somehow e.g. rendering its value in a React component etc.

1 Like

It’s also worth noting that this is not a limitation of ReScript. It’s how promises always work in JavaScript. Once a part of your app becomes async (via promises or otherwise) then everything that uses that part must be async as well.

6 Likes

thanks for the awesome information.