vertx 中的 future 和 promise 有什么区别?

What is the difference between future and promise in vertx?

我经常看到在 vert.x verticle 的开头使用 promisefuture。两者有什么具体区别吗? 我读过他们在 Scala 语言中的差异,在 Vert.x 的情况下是否也一样? 另外我什么时候应该知道什么时候使用承诺或未来?

Promise 用于定义非阻塞操作,它是 future() 方法returns Future 与承诺相关联,以获取承诺完成的通知并检索其值。 Future 界面是某个操作的结果,该操作可能已经发生,也可能还没有发生。

A Promise 也是可能已发生或尚未发生的操作的可写部分。 根据维基:

Given the new Promise / Future APIs the start(Future<Void>) and stop(Future<Void>) methods have been deprecated and will be removed in Vert.x 4.

请迁移到 start(Promise) 和 stop(Promise) 变体。

我读过的最好的:

think on Promise as producer (used by producer on one side of async operation) and Future as consumer (used by consumer on the other side).

Futures vs. Promises

游戏有点晚了,其他答案用不同的词说了很多,但这可能会有所帮助。假设您正在包装一些较旧的 API(例如基于回调)以使用 Futures,那么您可能会这样做:

Future<String> getStringFromLegacyCallbackAPI() {
   Promise<String> promise = Promise.promise();
   legacyApi.getString(promise::complete);
   return promise.future();
}

请注意,调用此方法的人会获得一个 Future,因此他们只能指定在成功完成或失败时应该发生什么(他们无法触发完成或失败)。所以,我认为你不应该将 promise 传递到堆栈中 - 而是 Future 应该被交还并且 Promise 应该保持在可以解决或拒绝它的代码的控制之下。

换句话说,

A future is a read-only container for a result that does not yet exist, while a promise can be written (normally only once).

更多来自here