辅助函数中的 Scala async { await(...) } 无法编译且类型不匹配

Scala async { await(...) } in a helper function fails to compile with type mismatch

我正在尝试使用 Scala 的 asyncawait 来处理在 foldLeft 调用期间给出的未来,所以我编写了一个辅助函数来执行等待,因为我不能在嵌套函数中使用 await

  import scala.await.Await._
  def a(f: Future[T]): T = async {
    await(f)
  }

然而以上失败:

Error:(33, 38) type mismatch;
 found   : scala.concurrent.Future[T]
 required: T
      def a(f: Future[T]): T = async {
                            ^

我做错了什么?

正如错误所说,return 类型需要是 Future[T]。异步块总是 return 是未来。

Here是async和await的签名:

def async[T](body: T)(implicit execContext: ExecutionContext): Future[T]
def await[T](awaitable: Future[T]): T

可以看出asyncT => Future[T]的一个函数。您可能会注意到这与 Future { ... } 构造函数 AKA Future.apply 的签名相同。它只是构建一个未来。

魔法就在await。它从 future 中提取价值,因此您可以在编写 "normal" 外观代码的同时仍然处理 futures。

如果你想等待异步计算的结果,而不是在 async 块中使用 await,你应该使用 Await.result[T]async 块总是返回一个 Future,你只能在异步块内部使用 await 的结果。每当您在 async 块中重用等待的值时,它几乎等同于使用底层 Future.

onComplete 方法