当前位置: 首页 > 知识库问答 >
问题:

在Scala中处理多个Future

居晗日
2023-03-14

我想创建一个未来列表,每个未来都可能通过或失败,并整理成功未来的结果。我该怎么做?

val futures2:List[Future[Int]] = List(Future{1}, Future{2},Future{throw new Exception("error")})

问题1)我想等待每个未来完成2)我想从每个成功的未来收集返回值的总和,并忽略失败的回报值(所以我应该得到3)。

共有1个答案

文凯康
2023-03-14

您需要了解的一件事是……避免试图从未来期货中“获取”值。

您可以继续在未来主义的土地上运营。

val futureList = List(
  Future(1),
  Future(2),
  Future(throw new Exception("error"))
)

// addd 1 to futures
// map will propagate errors to transformed futures
// only successful futures will result in +1, rest will stay with errors
val tranformedFutureList = futureList
  .map(future => future.map(i => i + 1))

// print values of futures
// simimlar to map... for each will work only with successful futures
val unitFutureList = futureList
  .map(future => future.foreach(i => println(i)))

// now lets give you sum of your "future" values
val sumFuture = futureList
  .foldLeft(Future(0))((facc, f) => f.onComplete({
    case Success(i) => facc.map(acc => acc + i)
    case Failure(ex) => facc
  })

由于OP(@Manu Chanda)询问了如何从Promise中获取价值,因此我补充了一些关于Promise在Scala中的内容。

因此……首先,让我们谈谈如何在Scala中思考的未来。

如果您看到一个Future[Int],那么请尝试将其视为一个正在进行的计算,它“应该产生”一个Int。现在,计算可以成功完成并导致成功[Int]抛出异常并导致Failure[Throwable]。因此,您会看到诸如on完成恢复使用onFailure等函数,它们似乎在谈论计算。

val intFuture = Future {
  // all this inside Future {} is going to run in some other thread
  val i = 5;
  val j = i + 10;
  val k = j / 5;
  k
}

现在…什么是promise

井。。。顾名思义...promise [Int] 是对 Int 值的promise...而已。

就像父母promise给孩子某个玩具一样。请注意,在这种情况下...父母不一定已经开始得到那个玩具,他们只是promise他们会得到。

为了完成promise...他们首先必须开始工作才能完成它...上市了...从商店购买...回家吧...有时。。。他们很忙,所以...他们会要求别人带上那个玩具,继续做他们的工作......另一个人会试图把那个玩具带给父母(他可能无法买到它),然后他们会用他们从他那里得到的任何结果来完成promise。

因此...基本上Promise在其内部包装了Future“包装”Future“value”可以被视为Promise的值。

所以

println("Well... The program wants an 'Int' toy")

// we "promised" our program that we will give it that int "toy"
val intPromise = Promise[Int]()

// now we can just move on with or life
println("Well... We just promised an 'Int' toy")

// while the program can make plans with how will it play with that "future toy"

val intFuture = intPromise.future
val plusOneIntFuture = intFuture.map(i => i + 1)

plusOneIntFuture.onComplete({
  case Success(i) => println("Wow... I got the toy and modified it to - " + i)
  case Failure(ex) => println("I did not get they toy")
})

// but since we at least want to try to complete our promise
println("Now... I suppose we need to get that 'Int' toy")
println("But... I am busy... I can not stop everything else for that toy")
println("ok... lets ask another thread to get that")

val getThatIntFuture = Future {
  println("Well... I am thread 2... trying to get the int")
  val i = 1
  println("Well... I am thread 2... lets just return this i = 1 thingy")
  i
}

// now lets complete our promise with whatever we will get from this other thread
getThatIntFuture.onComplete(intTry => intPromise.complete(intTry))

上述代码将导致以下输出,

Well... The program wants an 'Int' toy
Well... We just promised an 'Int' toy
Now... I suppose we need to get that 'Int' toy
But... I am busy... I can not stop everything else for that toy
Well... I am thread 2... trying to get the int
Well... I am thread 2... lets just return this i = 1 thingy
Wow... I got the toy and modified it to - 2

promise不会帮助你从未来“获得”价值。异步进程(或Scala中的未来)只是在另一个时间轴上运行...你不能在你的时间线中“获得”他们的“价值”,除非你努力使你的时间线与流程的时间线本身保持一致。

 类似资料:
  • 问题内容: 我使用Scala将PostgreSQL表导入到spark作为数据框。数据框看起来像 我正在将此数据帧转换为log_dt的数据格式为。为此,我使用了以下代码,使用函数将log_dt转换为时间戳格式。 当我使用命令打印以打印tablereader1数据帧时,得到以下结果 如何保留微秒作为时间戳的一部分?任何建议表示赞赏。 问题答案: 毫秒 您可以使用接受Java SimpleDateFor

  • 问题内容: 我的Flask应用程序必须进行大量计算才能获取特定页面。在Flask执行该功能时,其他用户无法访问该网站,因为Flask忙于进行大量计算。 有什么方法可以使我的Flask应用程序接受来自多个用户的请求? 问题答案: 是的,将应用程序部署在其他WSGI服务器上,请参阅Flask部署选项文档。 Flask随附的服务器组件实际上仅用于开发应用程序时;即使可以将其配置为处理并发请求(从Flas

  • 表模式如下: 表A的主键[ID1(分区键)id2(分区键)id3(群集键)] 表B主键[ID1(分区键)id2(分区键)状态(聚类键)id3(聚类键)] 那么在卡桑德拉我该怎么解决呢?

  • 但我得到了NullPointerException任何人都可以帮忙

  • 问题内容: 在运行Linux 2.6.35+的系统中,我的程序创建了许多子进程并对其进行监视。如果子进程死了,我会进行一些清理并再次产生该进程。我经常在过程中获取信号。与异步使用。 当将信号处理程序用于非实时信号时,当信号处理程序针对特定信号运行时,必须阻止同一信号的进一步出现,以避免进入递归处理程序。如果此时有多个信号到达,则内核仅调用一次处理程序(当信号被解除阻塞时)。 使用时是否具有相同的行

  • 以下代码通过使用print语句模拟在线购物。我正在使用Future来模拟一个场景,在该场景中,我同时将多个商品添加到购物篮中(我正在添加购物篮中的每个偶数商品)。我希望最后,代码会打印有多少商品已添加到购物篮中。 > 我创建了 5 个 Future 对象(因此我期望结果为 5 个) 我将每个未来存储在一个列表中。 我使用for循环来等待每个未来的完成 我希望在所有期货执行之后,我选择他们的成功对象