konsoletyper / teavm

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

`thread is null` while doing async calls in exported function #928

Closed zlataovce closed 5 days ago

zlataovce commented 5 days ago

Not sure if I'm missing something, but I'm getting an odd error with a modification of the ajax example referenced in https://teavm.org/docs/runtime/coroutines.html:

Uncaught TypeError: thread is null
    t_Main_get$_asyncCall_$ http://<script url>:1102
    t_Main_get1 http://<script url>:1063
    t_Main_get0 http://<script url>:1040
    t_Main_get0$exported$0 http://<script url>:1146

The code in question:

package test;

import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSExport;
import org.teavm.jso.ajax.XMLHttpRequest;

import java.io.IOException;

public class Main {
    @JSExport
    public static void get0(String url) throws IOException {
        System.out.println(get(url));
    }

    @Async
    public static native String get(String url) throws IOException;

    private static void get(String url, AsyncCallback<String> callback) {
        var xhr = XMLHttpRequest.create();
        xhr.open("get", url);
        xhr.setOnReadyStateChange(() -> {
            if (xhr.getReadyState() != XMLHttpRequest.DONE) {
                return;
            }

            int statusGroup = xhr.getStatus() / 100;
            if (statusGroup != 2 && statusGroup != 3) {
                callback.error(new IOException("HTTP status: " +
                        xhr.getStatus() + " " + xhr.getStatusText()));
            } else {
                callback.complete(xhr.getResponseText());
            }
        });
        xhr.send();
    }
}

Generated output: https://hasteb.in/wvcjlMwZzfi3RpD TeaVM 0.10.0, Java 21 (Amazon Corretto), ES2015 module, minification disabled, optimization level none

konsoletyper commented 5 days ago

As expected. You can't use async methods directly from JavaScript. You need to start a new thread explicitly from get0 method

zlataovce commented 5 days ago

Ah, okay. I didn't see it before, thank you.