konsoletyper / teavm

Compiles Java bytecode to JavaScript, WebAssembly and C
https://teavm.org
Apache License 2.0
2.55k stars 261 forks source link

Processing Javascript Promises in Java #845

Closed aghasemi closed 2 months ago

aghasemi commented 8 months ago

Hi,

Is there an example of how to process the return value of a native function when it is a Promise?

To begin with, I had to add teavm-core to my dependencies so that I could have the Promise class (it wasn't added by the archetype).

Promise is not a subclass of JSObject. When I ran the following code:

Promise p =  callModule().cast();
p.then( obj -> {
            System.out.println(obj);
            System.out.println(obj.getClass());
            return null;
});

I got Uncaught TypeError: ia_Client_callModule$js_body$_1(...).$then is not a function. If I print the output object of callModule, it is [object Promise]. Is there an extra step required?

Thanks Best

konsoletyper commented 8 months ago

Promises declared in core module have nothing to do with JavaScript Promise class. There's no standard wrapper declared for Promise, so you need to write your own definition.

tryone144 commented 4 months ago

https://github.com/konsoletyper/teavm/pull/884 introduced JSPromise as an interface for native promises. This should cover the above use-case.