Why doesn't Promise have a get () function?

If you know that the promise has already been resolved, why can't you just call get() on it and get the value? Unlike using then(..) with a callback function.

So instead:

 promise.then(function(value) { // do something with value }); 

I want to make it a lot easier:

 var value = promise.get(); 

Java offers this for CompletableFuture , and I see no reason JavaScript could not offer the same.

+1
javascript promise
Jul 28 '17 at 16:23
source share
2 answers

Java get method "Expects if necessary to complete this future", i.e. blocks the current thread. We absolutely never want to do this in JavaScript, which has only one "stream".

It would be possible to integrate the methods into the API to synchronously determine which results the completion promises, but it is good that they did not. Having only one then method to get results when they are available makes things much easier, safer and more consistent. There is no use writing your own if-pending-then-this-else-this logic, it only opens up the possibilities for errors. Asynchrony is tough.

+4
Jul 28 '17 at 16:34
source share

Of course not, because the task will be executed asynchronously, so you cannot immediately get the result.

But you can use sync / wait to write sequential asynchronous code.

0
Jul 28 '17 at 16:47
source share



All Articles