译者注:原文出处http://danielwestheide.com/blog/2013/01/16/the-neophytes-guide-to-scala-part-9-promises-and-futures-in-practice.html,翻译:Thomas
在前一篇译文中,我介绍了Future类型,它的内在逻辑,以及如何使用它来写出可读性强且可可组合的异步执行代码。在文章里,我也提到Future只是完整拼图的一部分:它是一种只读类型,让你可以以一种优雅的方式来引用将被计算出的结果并且处理异常。为了让你能够从Future中读取到计算好的值,还需要让负责计算的代码有办法把计算好的值存起来。在本文中,我就会来说明如何借助Promise类型来实现,并提供一个如何在实际代码中使用Future和Promise的指南。
Promises
在前篇关于Future的文章中,我们写过一组传递给Future的伙伴对象的apply方法的代码,并且导入了ExecutionContext作为默认执行上下文,它就神奇的异步执行了那些代码,并且返回包装在Future中的结果。
虽然这是一种简单易行的方法来构造一个Future,还是有另外一种方法来生成Future实例并最终以成功或失败结束。Future提供一个仅用于查询的接口,Promise作为伙伴类型让你通过将结果置入来完成一个Future。这仅可以被完成一次。一旦Promise完成了,它就不能够被修改。
Promise实例总是被关联到一个Future实例。试着在REPL里再一次调用Future的apply试试,你一定会注意到Future返回的是Promise类型:
import concurrent.Future
import concurrent.ExecutionContext.Implicits.global
val f: Future[String] = Future { "Hello world!" }
// REPL output:
// f: scala.concurrent.Future[String] = scala.concurrent.impl.Pro