How to wait for several Futures?

前端 未结 8 888
故里飘歌
故里飘歌 2020-12-02 06:02

Suppose I have several futures and need to wait until either any of them fails or all of them succeed.

For example: Let there are 3 futures:

8条回答
  •  忘掉有多难
    2020-12-02 06:20

    You can use this:

    val l = List(1, 6, 8)
    
    val f = l.map{
      i => future {
        println("future " +i)
        Thread.sleep(i* 1000)
        if (i == 12)
          throw new Exception("6 is not legal.")
        i
      }
    }
    
    val f1 = Future.sequence(f)
    
    f1 onSuccess{
      case l => {
        logInfo("onSuccess")
        l.foreach(i => {
    
          logInfo("h : " + i)
    
        })
      }
    }
    
    f1 onFailure{
      case l => {
        logInfo("onFailure")
      }
    

提交回复
热议问题