Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Promise not have a get() function?

If you know that the Promise has already been resolved why can't you just call get() on it and receive the value? As opposed to using then(..) with a callback function.

So instead of doing:

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

I want to be able to do the much simpler:

var value = promise.get();

Java offers this for it's CompletableFuture and I see no reason why JavaScript couldn't offer the same.

like image 923
Roland Avatar asked Jul 28 '17 16:07

Roland


1 Answers

Java's get method "Waits if necessary for this future to complete", i.e. it blocks the current thread. We absolutely never want to do that in JavaScript, which has only one "thread".

It would have been possible to integrate methods in the API to determine synchronously whether and with what results the promise completed, but it's a good thing they didn't. Having only one single method, then, to get results when they are available, makes things a lot easier, safer and more consistent. There's no benefit in writing your own if-pending-then-this-else-that logic, it only opens up possibilities for mistakes. Asynchrony is hard.

like image 98
Bergi Avatar answered Oct 11 '22 19:10

Bergi