简体   繁体   English

未来的Scala地图

[英]Scala map over a Future

In the following example, what is the expected behaviour? 在下面的示例中,预期的行为是什么?

import scala.concurrent.ExecutionContext.Implicits.global
val someFuture = Future { 1+1 }.map(elem => {
  println("mapping immediately")
  elem.toString
})

someFuture.onComplete {
  case scala.util.Success(value) => println(s"Got the callback = $value")
  case Failure(e) => e.printStackTrace()
}

Is the following output always guaranteed? 是否始终保证以下输出?

mapping immediately
Got the callback = 2

It depends. 这取决于。

val someFuture = Future { 1+1 }.map(elem => {
  println("mapping immediately")
  elem.toString
})

someFuture will be executed eagerly and the println will be executed. 将会急切地执行someFuture并将执行println

someFuture.onComplete {
    case scala.util.Success(value) => println(s"Got the callback = $value")
    case Failure(e) => e.printStackTrace()
}

onComplete is an event listener for a Future . onCompleteFuture的事件侦听器。 This is called only when this future is completed, either through an exception, or a value , to apply the provided function. 仅在完成将来时(通过异常或value )才能调用此函数以应用提供的功能。

Therefore, it will always execute after the execution of the someFuture . 因此,它将始终在someFuture执行之后执行。

Assuming that the someFuture is not going to fail, the order 假设someFuture不会失败,则命令

`mapping immediately
 Got the callback = 2`

is guaranteed. 是保证的。

For what ever reason, if there's an exception thrown, then the result would change. 无论出于何种原因,如果引发异常,结果都会改变。 In that case Got the callback = 2 will not be printed and mapping immediately may or may not be printed. 在这种情况下Got the callback = 2不会打印Got the callback = 2并且可能会或可能不会mapping immediately打印mapping immediately

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM