await function
EthanLozano opened this issue · comments
It would be nice if the DeferredManager had an await
function similar to Javascript's await operator or
Google Promises' await function. The implementation could be similar to Google's Promises' await function implementation.
This is untested, but maybe something like this:
public static <T> T await(Promise<T, ? extends Throwable, ?> promise) {
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<T> returnResult = new AtomicReference<>();
AtomicReference<Throwable> returnError = new AtomicReference<>();
promise
.then(result -> {
returnResult.set(result);
latch.countDown();
})
.fail(fail -> {
returnError.set(fail);
latch.countDown();
});
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Throwable error = returnError.get();
if (error != null) {
throw new RuntimeException(returnError.get());
} else {
return returnResult.get();
}
}
Does promise.waitSafely
do what you are looking for?
I don't think so. The goal is to turn async code into synchronous code with as little extra code as possible. For example (from Google Promises):
Promise<Int> {
let minusFive = try await(calculator.negate(5))
let twentyFive = try await(calculator.multiply(minusFive, minusFive))
let twenty = try await(calculator.add(twentyFive, minusFive))
let five = try await(calculator.subtract(twentyFive, twenty))
let zero = try await(calculator.add(minusFive, five))
return try await(calculator.multiply(zero, five))
}
However, since jdeferred isn't A+ compliant (doesn't catch exceptions thrown within a then
block), I've started using a different Java promises library.