首页 > 解决方案 > 未调用未来的 onComplete 回调

问题描述

标签: scalaplayframework

解决方案


你的逻辑没有错。我建议您尝试进行一些修改。

import org.slf4j.LoggerFactory

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

object FutureOnComplete extends App {

  private val logger = LoggerFactory.getLogger("test")

  def logElapsedTime[T](f: => Future[T], description: String): Future[T] = {
    val start = System.currentTimeMillis()
    f.onComplete(
      _ =>
        logger.warn(
          s"$description took [${System.currentTimeMillis() - start}]"))
    f
  }

  val f = for {
    _ <- logElapsedTime(Future(1), "1st task to be executed")
    result <- logElapsedTime(Future(2), "2nd task to be executed")
    _ <- logElapsedTime(Future(2), "3rd task to be executed")
    _ <- logElapsedTime(Future(2), "4th task to be executed")
  } yield result

  f.onComplete {
    case Success(v) =>
      logger.info(s"tasks succeeded !!!! $v")
    case Failure(ex) =>
      logger.error(ex.getMessage)
      throw ex
  }

  StdIn.readLine()

}
  • 提高日志级别以warn确保您的日志记录不会受到指责。或将其替换为println
  • 例如,在您的主线程中等待将来完成StdIn.readLine()。这允许异步进程完成并 onComplete 运行。
  • 使用=> Future[T]name 参数在方法内部开始执行 future logElapsedTime。这只是在未来开始时改变,而不是日志记录的逻辑

推荐阅读