【问题标题】:how get the result of Future without using "await"如何在不使用“await”的情况下获得 Future 的结果
【发布时间】:2017-06-08 23:54:28
【问题描述】:

我想在不阻塞操作的情况下获得 Future 的结果。 如果我用“await”编写代码,它可以工作,但对我不利,因为它会阻塞:

val t: Future[MatchResult[Personne]] = db.getPersonne(userId).map(_.get must beEqualTo(personne))
t.await

我尝试使用map 更改我的代码:

 val r: Future[MatchResult[Personne]] = db.getPersonne(userId).map(_.get must beEqualTo(personne))
   r.map {
     case r@isWhatIExpected => r
     case isNot => isNot
   }

但我有这个错误:

发现: scala.concurrent.Future[org.specs2.matcher.MatchResult[Personne]]
[错误] 必需:org.specs2.specification.create.InterpolatedFragment

【问题讨论】:

  • 当您处于Future 上下文中时,不等待就无法摆脱它。但是,您可以使用 onComplete 在结果准备好时使用它。
  • 您的问题似乎是关于 spec2 而不是一般的期货。一般来说,您可以使用fut.foreachfut.map 继续处理未来的价值观。

标签: scala asynchronous future specs2


【解决方案1】:

使用 Specs2 的样子,有一些助手可以测试异步函数。

import org.specs2.concurrent.{ExecutionEnv => EE}

"Foo" in { implicit ee: EE => // take care of ee
  myAsyncFunWithFuture must beEqualTo(expectedVal).await(timeToWait)
}

【讨论】:

  • 对不起,我不明白你的回答。你可以多解释一下
  • 没有必要使用 Scala Await 来测试使用 Specs2,只要你正确地以 .await 助手结束,maped val 不是这种情况。跨度>
  • Afaik,你甚至不需要导入 ExecutionEnv,也不需要隐式
  • C4stor 在这个答案中你使用 await 但它是阻塞的
  • @C4stor 如果您仔细阅读 Specs2 documentation,您可以阅读“等待/尝试方法需要隐式 org.specs2.concurrent.ExecutionEnv”
【解决方案2】:

@user4650183 我想我不明白你的问题。在使用结果之前,某个地方必须等待,或者如果您愿意,可以阻止它。

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2012-10-11
    • 1970-01-01
    • 2017-12-29
    • 2013-11-20
    • 1970-01-01
    相关资源
    最近更新 更多