我這裏粘貼兩種方法的執行。 在英語方面的差異低於 並返回函數的結果作爲新的未來
/** Creates a new future by applying a function to the successful result of
* this future. If this future is completed with an exception then the new
* future will also contain this exception.
*
* $forComprehensionExamples
*/
def map[S](f: T => S)(implicit executor: ExecutionContext): Future[S] = { // transform(f, identity)
val p = Promise[S]()
onComplete { v => p complete (v map f) }
p.future
}
/** Creates a new future by applying a function to the successful result of
* this future, and returns the result of the function as the new future.
* If this future is completed with an exception then the new future will
* also contain this exception.
*
* $forComprehensionExamples
*/
def flatMap[S](f: T => Future[S])(implicit executor: ExecutionContext): Future[S] = {
import impl.Promise.DefaultPromise
val p = new DefaultPromise[S]()
onComplete {
case f: Failure[_] => p complete f.asInstanceOf[Failure[S]]
case Success(v) => try f(v) match {
// If possible, link DefaultPromises to avoid space leaks
case dp: DefaultPromise[_] => dp.asInstanceOf[DefaultPromise[S]].linkRootOf(p)
case fut => fut.onComplete(p.complete)(internalExecutor)
} catch { case NonFatal(t) => p failure t }
}
p.future
}
從實施不同的是,flatMap與實際結果的承諾完成時調用函數。
case Success(v) => try f(v) match
對於一個偉大的文章閱讀:HTTP // danielwestheide.com /博客/ 2013/01/16 /的,新手引導到斯卡拉部分-9-承諾和期貨-IN-實踐。html
我認爲這有助於更好地理解它 - 爲什麼我們使用flatMap http://raichoo.blogspot.com/2011/07/from-functions-to-monads-in-scala.html – Phil