java - 在 vert.x 中按顺序减少 Future

标签 java promise future vert.x

在我的项目中,我使用 Java 中 vert.x 的 Future 实现。到目前为止一切都很顺利。但是,目前我在按顺序对对象列表执行操作时遇到问题。问题在于 Java 中的 reduce 方法分别“减少”和“组合”结果。这导致所有操作同时启动。正如在 easy 方法中所见,实现顺序执行是可能的。

private Future<Void> action(String object) {
    System.out.println("started " + object);
    Future<Void> f = Future.future();
    vertx.setTimer(1000, res -> {
        System.out.println("doing " + object);
        f.complete();
    });
    return f;
}

private void easy() {
    action("one")
        .compose(ignore -> action("two"))
        .compose(ignore -> action("three"))
        .setHandler(ignore -> System.out.println("completed"));
}

private void list() {
    List<String> l = new ArrayList<>();
    l.add("one");
    l.add("two");
    l.add("three");

    Future<Void> f = Future.future();
    l.stream().reduce(f,
        (f1, s) -> action(s),
        (f1, f2) -> f2.compose(ignore -> f1)
    ).setHandler(res -> {
        System.out.println("completed");
    });
}

执行easy时的输出:

started one
doing one
started two
doing two
started three
doing three
completed

执行列表时的输出:

started one
started two
started three
doing one
doing two
doing three
completed

Javascript 中的相同代码片段也有效,因为reduce 函数在一步中完成减少和合并:

function action(object) {
  return new Promise((resolve, reject) => {
    console.log("started " + object)
    window.setTimeout(() => {
      console.log("doing " + object);
      resolve()
    }, 1000);
  });
}

function easy() {
  action("one")
    .then(() => action("two"))
    .then(() => action("three"))
    .then(() => console.log("completed"));
}

function list() {
  l = ["one", "two", "three"]
  l.reduce((p, s) => p.then(() => action(s)), Promise.resolve())
    .then(() => console.log("completed"));
}

// easy()
list()

easylist的输出与Java代码的easy方法相同。我正在寻找的是一种修复Java中的reduce方法的方法,或者是实现相同结果的替代方法。

最佳答案

好的。我找到了 FoldLeft 方法的实现 here现在顺序执行工作正常...

private void list() {
    List<String> l = new ArrayList<>();
    l.add("one");
    l.add("two");
    l.add("three");

    Future<Void> f = Future.succeededFuture();

    foldLeft(l.iterator(), f,
        (f1, s) -> f1.compose(ignore -> action(s)))
        .setHandler(res -> {
            System.out.println("completed");
        });
}

private static <A, B> B foldLeft(Iterator<A> iterator, B identity, BiFunction<B, A, B> bf) {
    B result = identity;
    while(iterator.hasNext()) {
        A next = iterator.next();
        result = bf.apply(result, next);
    }
    return result;
}

关于java - 在 vert.x 中按顺序减少 Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51513678/

相关文章:

java - camera.setPreviewDisplay(SurfaceHolder) 上的异常

javascript - 在数组javascript的排序功能中实现异步/等待

c++ - 如何在列表中存储自删除 future

java - Java固定大小的线程池和所有CPU内核的最佳用法

java - 通过 ANT 部署到 Tomcat

java - 我如何连续在文本文件中写入java输出

java - 将格式化字符串写入文件 - Java

node.js - Sequelize reload() 清除所有模型数据

javascript - Angular2 promise : How to use the response from Http Get

Node.js、Synchronize.js 和返回值