Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of a Javascript Promise in a synchronous way [duplicate]

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...").

like image 709
Mariano Ruiz Avatar asked May 13 '16 23:05

Mariano Ruiz


People also ask

How do you resolve a promise in a synchronous function?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

How do you retrieve the value of a promise?

then() method to access the value of a promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value of the promise as a parameter.

Can a promise handle synchronous?

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.

How can I synchronously determine a JavaScript promise's state?

The best place to know if a promise is resolved is in . then(). Testing if a Promise is fullfilled would create a polling loop which is most likely the wrong direction. async/await is a nice construct if you'd like to reason async code synchronously.


1 Answers

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.

like image 73
jfriend00 Avatar answered Sep 24 '22 16:09

jfriend00