graalvm js Promise 使用
graalvm 对于js 的处理也是支持Promise 的,但是我们的java 对象需要实现PromiseExecutor 接口
接口定义
这个是官方文档的说明,但是实际没找到,变通方法可以通过BiConsumer 解决
@FunctionalInterface
public interface PromiseExecutor {
void onPromiseCreation(Value onResolve, Value onReject);
}
参考使用
- MyLogin.java
public class MyLogin implements BiConsumer<Value, Value> {
@Override
public void accept(Value resolve, Value reject) {
resolve.execute("OK");
}
public String logintoken(String username,String password) {
return String.format("%s------%s",username,password);
}
}
- js 代码
function mylogin(){
var BigDec = Java.type('java.math.BigDecimal');
var bd = new BigDec("0.1");
var login = Java.type("MyLogin")
console.dir(login);
var applogin = new login()
console.dir(applogin);
console.log(applogin.logintoken("dalong","demoapp"))
new Promise(applogin).then((data)=>{
console.log(data)
}).catch((err)=>{
console.log(err)
})
console.log(bd.add(bd).toString());
return "dalong rong feng"
}
- 代码调用
Engine engine = Engine.newBuilder().option("js.load-from-url","true").allowExperimentalOptions(true).build();
public static void loadURL(Engine engine) throws IOException {
Context context = Context.newBuilder().allowAllAccess(true).allowHostClassLoading(true).allowIO(true).engine(engine).build();
Source mysource =Source.newBuilder("js"," load(\"http://127.0.0.1:8080/mylogin.js\")","rongdemo").build();
context.eval(mysource);
Value callapp = context.getBindings("js").getMember("mylogin");
System.out.println(callapp.execute());
}
- 运行效果