Search code examples
gwtgxtjsni

Passing a Java callback in GWT to JSNI method which returns a Promise?


I am new to Promises and need some advice on how to handle a returned Promise in a JSNI method called from Java. Can't use JsInterop due to older version 2.7 of GWT. Any advice is appreciated.

Thanks for your time!


Solution

  • If you just have to read properties on the return object, you may try treating it as JSONObject.

    Alternatively you could call a method of your Java object in the resolver function of the promise to check conditions to decide if you want to resolve/reject. p.then() could be called with onFulfilled/onRejected functions just wrapping Java method calls to handle the result.

    Example:

    public class PromiseWrapper {
    
        boolean evaluate(String value) {
            return value != null ? true : false;
        }
    
        void onFulfilled(String value) {
            // use value
        }
    
        void onRejected(Strin reason) {
            // use reason
        }
    
        public native void doSomethingAynchronously() /*-{
            var p = new Promise(
                function(resolve, reject) {
                    var value = null; // Get value from somewhere
                    if([email protected]::evaluate(Ljava/lang/String;)(value)) {
                        resolve(value);
                    }
                    else {
                        reject("Because");
                    }
                }
            );
            p.then(function(value) {
                    [email protected]::onFulfilled(Ljava/lang/String;)(value);
                }, 
                function(reason) {
                    [email protected]::onRejected(Ljava/lang/String;)(reason);
                }
            );
        }-*/;
    
    }
    

    This is an untested example.