I need to get the value of a Javascript Promise object in a synchronous way.
I know how it works a Promise object in Javascript, and its advantages, and how to process the value with the then
method, but there are use cases, specially with Node.js (but this could apply to browser engines also) where you need to return just the value, but you are calling an API that returns a Promise objects instead, and you can't change the signature of that API, or the consumer API.
In Java language for example, you have the get()
method, that allows you wait if necessary for complete the action (blocks the execution), and then returns its result. Even you have a get(timeout,unit)
with the maximum time to wait before launch an TimeoutException
if the wait timed out.
The problem I have is something like this:
api1.setCallBackThatHasToReturnANoPromiseValue(
function(p1, p2) {
return api2.getPromisedValue(p1,p2) // This returns a Promise
.get() // -> but something like this
// could get the value in a sync way
}
);
Can someone tell me if I can resolve this with async programing?
And regardless of my specific problem that could be fixed with async code, there is a way to get the value of a Promise in a sync way (I know it will block the execution and all the performance issues, please avoid the "bla bla...").