2

我在这里看到了一个例子:

val fut = Future { ... // 我的 body 函数 } // 我的 body 函数从这里开始
fut onComplete { ... // 我的回调 }

看起来我可以在我的身体功能完成后添加回调。它仍然被调用吗?无论如何,我宁愿在我的函数开始运行之前向未来添加回调。是否有意义 ?我怎样才能做到这一点 ?

4

3 回答 3

7

该文档非常清楚您的第一点:

如果注册回调时future已经完成,那么回调可以异步执行,也可以在同一个线程上顺序执行。

至于您的后一个问题-您可以将需要运行的代码作为未来正文的第一行,例如:

def futureWithBefore[T](body: => T, before: => Any) = future {
  before()
  body()
} 
于 2013-05-14T17:46:39.970 回答
1

或类似的东西:

$ skala
Welcome to Scala version 2.11.0-20130423-194141-5ec9dbd6a9 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_06).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :pa
// Entering paste mode (ctrl-D to finish)

import scala.concurrent._
import ExecutionContext.Implicits.global

// Exiting paste mode, now interpreting.

import scala.concurrent._
import ExecutionContext.Implicits.global

scala> val x = Future { Thread sleep 60000L ; 7 }
x: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@44b0c913

scala> def todo = println("Extra work before the job.")
todo: Unit

scala> def something(i: Int) = { todo ; i }
something: (i: Int)Int

scala> x map something
res0: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@2a5457ea

scala> def f(i: Int) = { println(s"Job $i"); i+1 }
f: (i: Int)Int

scala> .map (f)
res1: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@32bc46f4

scala> .value
res2: Option[scala.util.Try[Int]] = None

scala> Await result (res1, duration.Duration("60 seconds"))
Extra work before the job.
Job 7
res3: Int = 8

是的,我需要一分钟来输入。

于 2013-05-14T19:56:53.150 回答
1

如果你想控制未来的执行点,你可以用Promise.

import scala.concurrent._
import ExecutionContext.Implicits.global

val initialPromise = promise[Unit]

// add your computations
val fut = initialPromise.future map { _ => println("My Future") }

// register callbacks
fut onComplete { _ => println("My Callback") }

// run
initialPromise.success()

使用其他东西Unit可以让你用任意值来提供计算。

于 2013-05-14T18:41:19.077 回答