| 7 | import java.util.concurrent.CompletableFuture; |
| 8 | |
| 9 | public class Async { |
| 10 | |
| 11 | private CompletableFuture<Object> future; |
| 12 | |
| 13 | private final JSCallFunction success = args -> { |
| 14 | future.complete(args != null && args.length > 0 ? args[0] : null); |
| 15 | return null; |
| 16 | }; |
| 17 | |
| 18 | private final JSCallFunction error = args -> { |
| 19 | String msg = args != null && args.length > 0 && args[0] != null ? args[0].toString() : ""; |
| 20 | future.completeExceptionally(new Exception(msg)); |
| 21 | return null; |
| 22 | }; |
| 23 | |
| 24 | private Async() { |
| 25 | this.future = new CompletableFuture<>(); |
| 26 | } |
| 27 | |
| 28 | public static CompletableFuture<Object> run(JSObject object, String name, Object... args) { |
| 29 | return new Async().call(object, name, args); |
| 30 | } |
| 31 | |
| 32 | private CompletableFuture<Object> call(JSObject object, String name, Object... args) { |
| 33 | JSFunction func = object.getJSFunction(name); |
| 34 | if (func == null) return empty(); |
| 35 | call(func, args); |
| 36 | return future; |
| 37 | } |
| 38 | |
| 39 | private CompletableFuture<Object> empty() { |
| 40 | future.complete(null); |
| 41 | return future; |
| 42 | } |
| 43 | |
| 44 | private void call(JSFunction func, Object... args) { |
| 45 | try { |
| 46 | Object result = func.call(args); |
| 47 | if (result instanceof JSObject) then((JSObject) result); |
| 48 | else future.complete(result); |
| 49 | } catch (Throwable e) { |
| 50 | future.completeExceptionally(e); |
| 51 | } finally { |
| 52 | func.release(); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | private void then(JSObject promise) { |
| 57 | JSFunction then = promise.getJSFunction("then"); |
| 58 | if (then == null) { |
| 59 | future.complete(promise); |
| 60 | } else { |
| 61 | consume(then, success); |
| 62 | consume(promise.getJSFunction("catch"), error); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | private void consume(JSFunction func, JSCallFunction callback) { |