Skip to main content
 首页 » 编程设计

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

2025年05月04日189luoye11

在我的项目中,我使用 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; 
}