How do I wait for asynchronous tasks to complete in scala?

后端 未结 1 1971
别跟我提以往
别跟我提以往 2020-12-24 08:30

I\'m aware that my problem might seem a little bit complex. But I\'ll try to express myself well.

I have this method which I want to return a Map[String, List[

相关标签:
1条回答
  • 2020-12-24 08:50

    Use scala.concurrent.{Future, Promise}:

    def doAsyncAction: Promise[T] = {
      val p = Promise[T]
      p success doSomeOperation
      p
    }
    
    def useResult = {
       val async = doAsyncAction;
       // The return of the below is Unit.
       async.future onSuccess {
          // do action.
       };
    };
    

    Another way is to Await the result. (this is a blocking action).

    Used when you need to return the result

    import scala.concurrent.{ ExecutionContext, ExecutionContext$, Future, Promise, Await }
    import scala.concurrent.duration._
    
    def method: Option[T] = {
       val future: Future[T] = Future {
           someAction
       }
       val response = future map {
           items => Some(items)
       } recover {
           case timeout: java.util.concurrent.TimeoutException => None
       }
       Await.result(future, 5000 millis);
    };
    

    Be careful to execute blocking Futures in their own executor, otherwise you end up blocking other parallel computation.

    0 讨论(0)
提交回复
热议问题