Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

await function #169

Open
EthanLozano opened this issue Nov 9, 2018 · 3 comments
Open

await function #169

EthanLozano opened this issue Nov 9, 2018 · 3 comments

Comments

@EthanLozano
Copy link

EthanLozano commented Nov 9, 2018

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.

@EthanLozano
Copy link
Author

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();
    }
}

@saturnism
Copy link
Member

Does promise.waitSafely do what you are looking for?

@EthanLozano
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants