操作演示

推演

在不使用 map flatmap的情况下 多个future 如果相互之间有依赖关系 则通常是嵌套调用 嵌套太多则维护性太差

比如

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
val f1 = Future {
TimeUnit.SECONDS.sleep(1)
"f1"
}

f1 onSuccess {
case str =>
  val f11 = Future { // 启动另一个future
    // Future{ 。。。 } // 再启动另一个future
    if (3 > 2) println(str)
    else throw new Exception("出错了")
  }

  f11 onSuccess {
    case _ => println(s"收到结果 ${str}")
  }
}

map flatmap 示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

val f44 :Future[String]= Future {
"start"
} map { case one =>
11
} map { two =>
22
} flatMap { xx =>
println("do something 33")
val f4 = Future {
  "end"
}
println("do something 44")
f4
}

val str = Await.result(f44, Duration.create(3, TimeUnit.SECONDS))
println("done--main--" + str)

二者差异

map和flatMap都可以以链式书写future调用

二者的区别是:
map 的表达式已经被包装成1个新future返回 flatMap 必须手动创建1个新future作为返回值, 但可以在中间做点其他事情