Multithreading 从使用未来序列的方法返回计算列表

Multithreading 从使用未来序列的方法返回计算列表,multithreading,scala,concurrency,promise,future,Multithreading,Scala,Concurrency,Promise,Future,我想从使用未来列表的方法返回计算列表: def foo: List[Long] = { val res = List(1, 2, 3) map { x => Future { someCalculation(x) } } Future.sequence(res) // what to do next? } def someCalculation(a: Int): Long = //.... 我该怎么做呢?谈到未来,有一点需要理解:如果你想从Future[T]

我想从使用未来列表的方法返回计算列表:

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

  Future.sequence(res)
  // what to do next?
}


def someCalculation(a: Int): Long = //....

我该怎么做呢?

谈到未来,有一点需要理解:如果你想从
Future[T]
转到
T
,你需要等待操作的结果,但这是你希望避免的,以免影响程序的性能。正确的方法是尽可能多地使用异步抽象,并将阻塞移到调用堆栈

Future类有许多方法可用于连接其他异步操作,如map、onComplete、onSuccess等

如果您确实需要等待结果,则会出现
wait.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)

谈到未来,有一个关键点需要理解:如果你想从
Future[T]
转到
T
,你需要等待操作的结果,但这是你希望避免的,以免影响程序的性能。正确的方法是尽可能多地使用异步抽象,并将阻塞移到调用堆栈

Future类有许多方法可用于连接其他异步操作,如map、onComplete、onSuccess等

如果您确实需要等待结果,则会出现
wait.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)

好的,使用
Future
的全部目的是使其异步化。i、 e

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)

好的,使用
Future
的全部目的是使其异步化。i、 e

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)

像往常一样,您可以用
Future.traverse(x)(fn)
的单个步骤替换
Future.sequence(x.map(fn))
的两个步骤,也可以像往常一样,用
Future.traverse(x)(fn)
的单个步骤替换
Future.traverse(x)(fn)