Search code examples
javafuturegremlintinkerpop

Using a Promise to return java Tinkerpop Gremlin Traversal results


I would like to leverage the .promise(final Function<Traversal<S, E>, T> traversalFunction) method of a Gremlin GraphTraversal. It's not clear to me what function I would use within the promise.

Using the Tinkerpop Client object, I do something like this:

GraphTraversal myTraversal = g.V().hasLabel("myLabel");
client.submitAsync(myTraversal)
        .thenAccept(result -> {
            List<Map<Object, Object>> resultList = new ArrayList<>();
            result.iterator().forEachRemaining(item ->{
                DefaultRemoteTraverser drt = (DefaultRemoteTraverser) item.getObject();
                Map<Object, Object> itemMap = (HashMap) drt.get();
                resultList.add(itemMap);
            });
            outputSuccess(resultList);
        })
        .exceptionally(throwable -> {
            // handle;
            return null;
        })

What would the equivalent look like using .promise()? I looked for a test in the source repo that might provide a clue, but did not see one.


Solution

  • First note that the promise() can only be use if you are using the Traversal as a remote connection. It will throw an exception in embedded mode as explained in the javadoc.

    The promise() takes a function that processes the Traversal after it has been submitted asynchronously to the server. You're really just providing a terminator to the promise() to get a result into the returned CompletableFuture:

    g.V().out().promise(t -> t.toList());
    

    I guess you could chain it to be more exactly like what you had in your example:

        g.V().out().promise(t -> t.toList()).
          thenAccept(r -> outputSuccess(r)).
          exceptionally(...);