gpt4 book ai didi

callback - Vert.x 是 "based on callbacks"(而不是 future )是什么意思?

转载 作者:行者123 更新时间:2023-12-04 04:06:51 27 4
gpt4 key购买 nike

在谈到 future 和回调时,documentation说是

The Vert.x core APIs are based on callbacks to notify of asynchronous events. The seasoned developer will naturally think that this opens the door to the so-called "callback hell" where multiple levels of nested callbacks render the code difficult to comprehend as illustrated by this fictional code:

foo.a(1, res1 -> {
if (res1.succeeded()) {
bar.b("abc", 1, res2 -> {
if (res.succeeded()) {
baz.c(res3 -> {
dosomething(res1, res2, res3, res4 -> {
// (...)
});
});
}
});
}
});

While the core APIs could have been designed to favor promises and futures, the choice of callbacks as the cardinal model is actually interesting since it allows different programming abstractions to be used.

  1. “Vert.x 核心 API 基于回调”是什么意思?如果它基于 future 会有什么不同?
  2. “回调作为基本模型”是什么意思?

最佳答案

  1. 这意味着 Vert.x 核心异步 API 都将回调作为输入,并使用该回调来处理对 API 调用的异步结果的 react 。如果它基于 Futures,而不是像这样的 API:

      void deployVerticle(Verticle verticle, Handler<AsyncResult<String>> 
    completionHandler);

    看起来像这样:

    Future<String> deployVerticle(Verticle verticle);

    因此,与其采用获得 AsyncResult<String> 的回调,不如采用回调作为输入,它返回一个 Future<String> .然而,Vert.x team is moving to a hybrid Callback/Future-based model in Vert.x 4.0 ,因此在不久的将来,这两种 API 都将成为核心 Vert.x API 的一部分。

  2. 我认为这里使用 cardinal 表示“基本”。所以这只是意味着 Vert.x 本身在其自己的实现中使用了回调。然后它使用代码生成和/或其他技术来派生其他类型的 API 抽象。类似于返回 Futures 或返回 RxJava 的 API类型,或者可以用作 Kotlin coroutines

一般来说,Future 比回调更容易使用,尤其是当您必须将多个异步操作组合在一起时。例如,您在原始问题中包含的代码可能使用 Futures 编写如下:

CompositeFuture.all(foo.a(1), bar.b("abc", 1), baz.c())
.compose(fut -> doSomething(fut.resultAt(0), fut.resultAt(1),
fut.resultAt(2)))
.compose(res4 -> ...)

关于callback - Vert.x 是 "based on callbacks"(而不是 future )是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62329372/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com