You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中替代onComplete获取最先完成Future的实现方案

Scala 实现返回率先完成Future的方法(不用onComplete)

首先完全可以不用onComplete实现需求,这里提供两种常见的可行思路:

思路1:直接调用标准库内置API(推荐新手使用)

Scala的Future伴生对象已经原生提供了firstCompletedOf方法,专门用来返回多个Future中最先完成的实例,仅需一行代码就能实现:

import scala.concurrent.Future

def first[A](f1: Future[A], f2: Future[A]): Future[A] = 
  Future.firstCompletedOf(List(f1, f2))

这种写法不需要你自己处理回调逻辑,也完全不用写onComplete,标准库已经帮你封装了所有底层逻辑,稳定性更高。

思路2:手动实现,用transform方法替代onComplete

如果你希望自己手写核心逻辑,不想直接调用封装好的API,可以用transform方法替换原来的onComplete回调,核心逻辑和你已知的Promise实现思路一致:

import scala.concurrent.{Future, Promise}

def first[A](f1: Future[A], f2: Future[A]): Future[A] =
  val promise = Promise[A]()
  // transform会接收Future的完成结果(成功/失败都包含),处理后返回原结果即可
  f1.transform(result => {
    promise.tryComplete(result)
    result
  })
  f2.transform(result => {
    promise.tryComplete(result)
    result
  })
  promise.future

原理说明

两种实现的核心都依赖Promise.tryComplete的特性:它只会在Promise还没被赋值的时候生效,第一个完成的Future会率先给Promise赋值,第二个完成的Future调用tryComplete会直接返回false,不会覆盖已有结果。哪怕率先完成的是执行失败的Future,也会正常返回,符合「率先执行完成」的判定规则(无论成功失败都算完成)。


内容的提问来源于stack exchange,提问作者Gabriel Santana Paredes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 21:57:01