GraalVM JavaScript in Java - How to identify an async method

717 views Asked by At

Consider we have the following JS code:

    async function helloAsync(){
        return "Hello";
    }

    function hello(){
        return "Hello";
    }

In Java, you can load this code into a GraalVM context object using:

    context.eval("js", mappingTemplate);

Giving us two members that we can evaluate using:

    Value bindings = context.getBindings("js");
    final Value executionResult1 = bindings.getMember("hello")
                        .execute();
    final Value executionResult2 = bindings.getMember("helloAsync")
                        .execute();

As a result, the executionResult2 would be a promise that can be completed within Java. My question is how I can reliably tell that executionResult2 is in fact a promise, and not just a string like executionResult1. Currently, a naive and unreliable approach could be:

if (executionResult.toString().startsWith("Promise") &&
                    executionResult.hasMember("then") && executionResult.hasMember("catch"))

What are more reliable/elegant ways of recognizing a promise returned from JS?

2

There are 2 answers

1
Sam YC On BEST ANSWER

Can you try to inspect the content via this value.getMetaObject().

The doc say:

Returns the metaobject that is associated with this value or null if no metaobject is available. The metaobject represents a description of the object, reveals it's kind and it's features. Some information that a metaobject might define includes the base object's type, interface, class, methods, attributes, etc.

Could be useful for your case.

0
Daniele Bonetta On

Yes, value.getMetaObject() is the way to go: it returns the JS constructor associated with the value instance, which should be Promise in your case.