Accessing value returned by scala futures

后端 未结 6 696
野趣味
野趣味 2020-12-01 01:54

I am a newbie to scala futures and I have a doubt regarding the return value of scala futures.

So, generally syntax for a scala future is

 def downl         


        
6条回答
  •  一生所求
    2020-12-01 02:29

    You can do something like that. If The wait time that is given in Await.result method is less than it takes the awaitable to execute, you will have a TimeoutException, and you need to handle the error (or any other error).

    import scala.concurrent._
    import ExecutionContext.Implicits.global
    import scala.util.{Try, Success, Failure}
    import scala.concurrent.duration._
    
    object MyObject {
        def main(args: Array[String]) {
    
            val myVal: Future[String] = Future { silly() }
    
            // values less than 5 seconds will go to 
            // Failure case, because silly() will not be done yet
            Try(Await.result(myVal, 10 seconds)) match {
                case Success(extractedVal) => { println("Success Happened: " + extractedVal) }
                case Failure(_) => { println("Failure Happened") }
                case _ => { println("Very Strange") }
            }      
        }
    
        def silly(): String = {
            Thread.sleep(5000)
            "Hello from silly"
            }
    }
    

提交回复
热议问题