GraalVM Java Java 中的脚本 - 如何识别异步方法

GraalVM JavaScript in Java - How to identify an async method

假设我们有以下 JS 代码:

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

    function hello(){
        return "Hello";
    }

在 Java 中,您可以使用以下方法将此代码加载到 GraalVM 上下文对象中:

    context.eval("js", mappingTemplate);

给我们两个可以评估的成员:

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

因此,executionResult2 将是一个可以在 Java 内完成的承诺。我的问题是如何可靠地判断 executionResult2 实际上是一个承诺,而不仅仅是像 executionResult1 这样的字符串。目前,一种幼稚且不可靠的方法可能是:

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

还有哪些 reliable/elegant 方法可以识别从 JS 返回的承诺?

您可以尝试通过 this value.getMetaObject().

检查内容吗

医生说:

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.

可能对您的情况有用。

是的,value.getMetaObject() 是要走的路:它 returns 与 value 实例关联的 JS 构造函数,在您的情况下应该是 Promise