使用graalvm.js调用promise

前提

1、JDK1.8

2、引入jar包

<!--graalvm.js -->
<dependency>
	<groupId>org.graalvm.js</groupId>
	<artifactId>js</artifactId>
	<version>1.0.0-rc12</version>
</dependency>

运行

package com.terwergreen;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;

import java.util.function.Consumer;


public class Main {
    private Object renderedObject = null;

    private Consumer<Object> fnResolve = object -> {
        renderedObject = object;
        System.out.println("fnResolve=>promiseResolved");
    };

    private Consumer<Object> fnRejected = object -> {
        renderedObject = object;
        System.out.println("fnRejected=>promiseRejected");
    };

    private void execute() {
        try (Context context = Context.newBuilder("js").allowAllAccess(true).build()) {
            Value eval = context.eval("js",
                    "(async function() { return 'Hello World' });"
            );
            eval.execute().invokeMember("then", fnResolve, fnRejected);

            System.out.println("renderedObject = " + renderedObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.execute();
    }
}
posted @ 2019-02-09 12:46  灯塔下的守望者  阅读(978)  评论(0编辑  收藏  举报