Scala Future未进入onComplete() [英] Scala Future not entering onComplete()

查看:274
本文介绍了Scala Future未进入onComplete()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从代码片段中获取值,结果是 Future ,但是当我运行代码时,事实证明,它永远不会进入 onComplete 函数。有没有什么我做错了?

I am trying to grab the value from a snippet of code that results in a Future, but when I run through the code, it turns out that it never enters the onComplete function. Is there anything I'm doing wrong?

我试过使用地图,因为它是在其他帖子中提出的,但没有成功

I've tried using a map as well since it was suggested in other posts, but haven't had success

override def findOrCreate(phoneNumber: String, creationReason: String): Future[AvroCustomer] = {

      //query for customer in db
      val avroCustomer: Future[AvroCustomer] = customerByPhone(phoneNumber)

      avroCustomer.onComplete({
        case Success(null) => {
          createUserAndEvent(phoneNumber, creationReason, 1.0)
        }

        case Success(customer) => {
            Future.successful(customer)
        }

        case Failure(exception) => {

        }
})


推荐答案

回答扩展评论。这个虚拟程序不会打印任何东西。

Answer to expand on the comment. This dummy program will not print anything.

import scala.concurrent.Future
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global

object Quickie {
  def main(args: Array[String]): Unit = {
    val addOneInFuture: Future[Int] = Future(addOne(3))

    addOneInFuture.onComplete {
      case Success(s) => println(s)
      case Failure(ex) => println(ex.toString)
      case _ => println("what the hell happened")
    }

  }

  def addOne(x: Int): Int = x + 1
}

我启动了一个新线程,但由于该值从不需要,所以我不会看到打印的4.但,添加一个简单的 Await Threed.sleep(_eternity _),甚至可以找到另一个 println ,你会看到结果。在Scala中理解 Futures 的一件事就是你想合成它们并将它们当作集合来对待(因此, for-comprehensions 为他们),你很少想要做些事情和打印。如果你做了一些数据库或休息IO,你将会进一步处理数据。

I fire up a new thread but since the value is never needed I will not see the printed 4. However, add a simple Await, Threed.sleep(_eternity_), heck even another println and you will see the result. One thing to understand about Futures in Scala is that you want to compose and treat them as collections (hence there're for-comprehensions for them) and you rarely want to do something and print. If you do some db or rest IO, you are going to process the data further anyway.

Daniel Westheide有一个旧的但黄金的博客系列,你可以阅读。
http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html

There's an old but gold blog series by Daniel Westheide that you could read. http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html

这篇关于Scala Future未进入onComplete()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆