2014-01-16 79 views

回答

4

有一个关键点理解,当谈到期货:如果你想要去的Future[T]T你需要等待操作的结果,但是这是你想避免不影响性能你的程序。正确的做法是尽可能多地继续使用异步抽象,并将阻塞移动到您的调用堆栈。

未来类有很多,你可以用它来迷住其他异步操作,如地图,的onComplete,的onSuccess,等等等等方法

如果你真的需要等待结果,再有就是Await.result

val listOfFutures:List[Future[Long]] = val res = List(1, 2, 3) map { 
    x => Future { someCalculation(x) } 
    } 

// now we have a Future[List[Long]] 
val futureList:Future[List[Long]] = Future.sequence(listOfFutures) 

// Keep being async here, compute the results asynchronously. Remember the map function on future allows you to pass a f: A=>B on Future[A] and obtain a Future[B]. Here we call the sum method on the list 
val yourOperationAsync:Future[Long] = futureList.map{_.sum} 

// Do this only when you need to get the result 
val result:Long = Await.result(yourOperationAsync, 1 second) 
+2

和往常一样,可以更换Future.sequence(x.map(FN))的'两个步骤'与'Future.traverse(x)(fn)'的单一步骤。 – Hugh

3

那么使用Future的整点就是使它异步。即

def foo: Future[List[Long]] = { 
    val res = List(1, 2, 3) map { 
    x => Future { someCalculation(x) } 
    } 
    Future.sequence(res) 
} 

这将是理想的解决方案。但万一如果你想等待,那么你可以等待结果,然后返回:

val ans = Future.sequence(res) 
Await.ready(ans, Duration.inf)