英文:
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中完成的 Promise。我的问题是,我如何可靠地判断 executionResult2
实际上是一个 Promise,而不仅仅是一个类似于 executionResult1
的字符串。目前,一种天真且不可靠的方法可能是:
if (executionResult.toString().startsWith("Promise") &&
executionResult.hasMember("then") && executionResult.hasMember("catch"))
有哪些更可靠/优雅的方法来识别JS返回的 Promise?
英文:
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?
答案1
得分: 2
你可以尝试通过此链接的value.getMetaObject()
来检查内容。
文档中说明:
> 返回与此值关联的元对象,如果没有可用的元对象,则返回null。元对象表示对象的描述,揭示了它的类型和特征。元对象可能定义的一些信息包括基本对象的类型、接口、类、方法、属性等。
可能对你的情况有用。
英文:
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.
答案2
得分: 1
是的,value.getMetaObject()
是正确的方法:它返回与value
实例关联的JS构造函数,在您的情况下应该是Promise
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论