Scala Future函数式组合子 之 andThen
源码中的doc说明:
将副作用函数应用于此Future的结果,并返回带有此未来结果的新未来。
该方法允许强制回调以指定的顺序执行。
注意,如果一个链接andThen回调函数抛出异常,该异常不会传播到后续的andThen回调函数。相反,后续的andThen回调函数被赋予这个future的原始值。
/**
Applies the side-effecting function to the result of this future, and returns a new future with the result of this future.
This method allows one to enforce that the callbacks are executed in a specified order.
Note that if one of the chained andThen callbacks throws an exception, that exception is not propagated to the subsequent andThen callbacks. Instead, the subsequent andThen callbacks are given the original value of this future.
*/
def andThen[U](pf: PartialFunction[Try[T], U])(implicit executor: ExecutionContext): Future[T] = {
val p = Promise[T]()
onComplete {
case r => try pf.applyOrElse[Try[T], Any](r, Predef.conforms[Try[T]]) finally p complete r
}
p.future
}
在前面的andThen失败后 原始值被传到了后面的andThen,每个andThen转换应用的不是同一个线程