Javascript – GraalVM JavaScript in Java – How to recognize asynchronous methods

GraalVM JavaScript in Java – How to recognize asynchronous methods… here is a solution to the problem.

GraalVM JavaScript in Java – How to recognize asynchronous methods

Consider that 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 the following methods:

    context.eval("js", mappingTemplate);

Give us two members we can evaluate:

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

Therefore, executionResult2 will be a promise that can be done in Java. My question is how to reliably tell executionResult2 is actually a promise, not just a string like executionResult1. Currently, a naïve and unreliable method could be:

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

What is a more reliable/elegant way to identify a promise returned from JS?

Solution

Can you try to check the content by this? value.getMetaObject()

The doctor said:

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.

May be useful for your situation.

Related Problems and Solutions