【发布时间】:2014-11-15 10:58:26
【问题描述】:
鉴于此代码将 List[Future[T]] 转换为 Future[List[T]]
def all[T](fs: List[Future[T]]): Future[List[T]] = {
val p = Promise[List[T]]() //create an empty promise which will contain the result (i.e. the future)
p.success(Nil) //initialise: the result of the promise is a Future of an empty list
fs.foldRight(p.future) { //accumulator is the future of the promise
(oneFutueFromTheList, accFutureOfAList) =>
for (
actualValueOfFuture <- oneFutueFromTheList; //unpack the item in the future
theList <- accFutureOfAList //unpack the list from the future
) yield actualValueOfFuture :: theList //append the item to the list
}
}
for 推导的产出是一个 List[T]。
为什么 foldRight 返回 Future[List[T]](而不是 List[T])?是不是因为 foldRight 的累加器是 Future[List[T]] 并且 foldRight 足够“聪明”,知道将收益率的结果 List[T] 放入 Future[List[T]] ?
代码来源:https://class.coursera.org/reactive-001响应式编程原理
【问题讨论】: