GWT: How to execute native js function passed as param (and thus not accessible globally)

442 Views Asked by At

Here's the minimal snippet of code to reproduce the problem I'm struggling with:

import java.util.function.Consumer;

public class NaivePromise<T> {

  public NaivePromise(Consumer<Consumer<T>> resolve) {
    super();
    create(resolve);
  }

  public native NaivePromise<T> create(Consumer<Consumer<T>> handler) /*-{
    return new Promise(function (resolve) {
      console.log("DBG NATIVE RESOLVE");
      [email protected]::accept(*)(resolve)
    });
  }-*/;


  public static void pong() {
    new NaivePromise<String>(resolve -> {
      resolve.accept("HERE WE'LL GET AN ERROR, SINCE RESOLVE IS ACTUALLY A NATIVE FUNCTION");
    });
  }

}

My question would be - how can I execute native functions passed as lambdas to GWT Consumer (or any other functional interface)?

1

There are 1 best solutions below

0
Thomas Broyer On BEST ANSWER

You'd have to make resolve a JavaScriptObject rather than a Consumer<String>, and use JSNI to call it:

private native void call(JavaScriptObject resolve, String arg) /*-{
  resolve(arg);
}-*/;

Though you actually really should use JsInterop here, with a @JsFunction interface; and probably actually just use Elemental 2's mapping of Promise.