I need to get the value of a Javascript Promise object in a
synchronous way.
You can't. If an API returns a promise that's because the operation is asynchronous. At the time your function returns, the value is simply not known yet and Javascript does not provide any mechanism to wait for the result before returning.
Instead, you have to design for an asynchronous response and your caller has to code for an asynchronous response. Since you're already using promises, that means your caller needs to use a .then()
handler on the promise to get access to the asynchronous result and that .then()
handler will get called some time in the future, long after the API call has already returned.
It's important to understand that Javascript in browsers and node.js is fundamentally different than Java. These Javascript environments are single threaded and event driven. That means you can't block and wait for something to happen before returning. Instead you have to return and let the event queue run so your async result can eventually be processed and trigger a callback. If you did try to block and wait for a result (some people trying making busy loops that just loop for a couple seconds to simulate a sleep()
call one might use in another language), you'd have a deadlock because the result could not be processed until you stopped blocking, but you wouldn't stop blocking until the result was ready. You'd just end up with an infinite loop.
So, instead you have to learn to program for async responses in Javascript, either via a plain callback or using promises and their associated .then()
handlers. And, all consumers of that async result have to know it's async and program accordingly.
In addition, a promise is a representation of a future value. You only get access to it with a .then()
handler that will be called when (sometime in the future) the value is ready or an error occurs. There is no synchronous way to get a value from a promise.