Difference Await.ready and Await.result

前端 未结 3 1034
误落风尘
误落风尘 2021-02-02 07:14

I know this is quite an open ended question and I apologize.

I can see that Await.ready returns Awaitable.type while Await.result

3条回答
  •  -上瘾入骨i
    2021-02-02 07:35

    Both are blocking for at most the given Duration. However, Await.result tries to return the future result right away and throws an exception if the future failed while Await.ready returns the completed future from which the result (Success or Failure) can safely be extracted via the value property.

    The latter is very handy when you have to deal with a timeout as well:

    val future = Future { Thread.sleep(Random.nextInt(2000)); 123 }
    
    Try(Await.ready(future, 1.second)) match {
        case Success(f) => f.value.get match {
          case Success(res) => // handle future success 
          case Failure(e) => // handle future failure
        }
        case Failure(_) => // handle timeout
    }
    

    When using Await.result, the timeout exception and exceptions from failing futures are "mixed up".

    Try(Await.result(future, 1.second)) match {
        case Success(res) => // we can deal with the result directly
        case Failure(e) => // but we might have to figure out if a timeout happened
    }
    

提交回复
热议问题