Composition d’opérations asynchrones
Apprenez à enchaîner et à combiner plusieurs `Futures` à l’aide de méthodes telles que `map`, `flatMap` et les compréhensions `for`.
Composition d’opérations asynchrones est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 2 sur 3. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 3 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Why Chain Async Operations?
Futures help us run tasks without blocking the main program. But what if one task's result is needed for another, or we need to combine results from multiple tasks?
This is where composing Futures comes in handy. We'll learn how to chain and combine these asynchronous operations, making your Scala code more powerful and responsive.
`map`: Transform a Future's Result
The map method is used when you have a Future and you want to transform its successful result into another value. The transformation function you provide will be applied once the Future completes successfully.
- It always returns a new
Future. - It's perfect for simple, synchronous transformations on an asynchronous result.
`map` in Action (Code)
Here, we get a number from a Future and then double it using map. The transformation happens only after the initial Future finishes.
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
val originalFuture: Future[Int] = Future {
Thread.sleep(100) // Simulate work
10
}
val doubledFuture: Future[Int] = originalFuture.map(value => value * 2)
val result = Await.result(doubledFuture, 1.second)
println(s"Doubled value: $result")
}
}`flatMap`: Chaining Futures
Sometimes, the successful result of one Future needs to kick off another Future. This is where flatMap shines. It "flattens" a Future of a Future (Future[Future[T]]) into a single Future[T].
- Use it when your transformation function returns a
Future. - It's essential for sequential asynchronous operations.
`flatMap` in Action (Code)
We fetch a user ID, then use that ID to fetch user details. Each step is an asynchronous operation returning a Future. flatMap ensures they run in sequence.
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
def fetchUserId(): Future[Int] = Future {
Thread.sleep(50)
123
}
def fetchUserDetails(userId: Int): Future[String] = Future {
Thread.sleep(100)
s"User $userId details"
}
val userDetailsFuture: Future[String] = fetchUserId().flatMap { userId =>
fetchUserDetails(userId)
}
val result = Await.result(userDetailsFuture, 1.second)
println(s"Details: $result")
}
}`map` vs. `flatMap`: Key Difference
It's common to confuse map and flatMap. Remember:
map: Your function returns a regular value (e.g.,Int,String).Future[A].map(A => B)results inFuture[B].flatMap: Your function returns anotherFuture(e.g.,Future[Int],Future[String]).Future[A].flatMap(A => Future[B])results inFuture[B].
flatMap is for chaining async operations, while map is for transforming an async result synchronously.
`for` Comprehensions: Elegant Chaining
Scala's for comprehensions provide a clean, readable syntax for chaining operations that involve map and flatMap. They are purely syntactic sugar, meaning the compiler translates them into a series of map, flatMap, and filter calls.
When you have multiple dependent Future operations, for comprehensions make the code look almost synchronous.
`for` Comprehension Code
This example uses a for comprehension to chain the same user ID and details fetching logic we saw with flatMap. Notice how much cleaner it looks!
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
def fetchUserId(): Future[Int] = Future {
Thread.sleep(50)
123
}
def fetchUserName(userId: Int): Future[String] = Future {
Thread.sleep(100)
s"Alice (ID: $userId)"
}
val userFuture: Future[String] = for {
id <- fetchUserId()
name <- fetchUserName(id)
} yield name
val result = Await.result(userFuture, 1.second)
println(s"User name: $result")
}
}`zip`: Combining Independent Results
What if you have two independent Futures and want to combine their results once both are complete? The zip method is perfect for this. It takes another Future and returns a new Future that holds a pair (a Tuple) of their successful results.
Both futures run concurrently, and zip waits for both to finish.
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
val futureA = Future {
Thread.sleep(100)
"Hello"
}
val futureB = Future {
Thread.sleep(50)
"World"
}
val combinedFuture: Future[(String, String)] = futureA.zip(futureB)
val (greeting, subject) = Await.result(combinedFuture, 1.second)
println(s"$greeting $subject!")
}
}Quick Check: Composing Futures
Consider the following Scala code snippet. What will be the final value printed?
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
val f1 = Future { 5 }
val f2 = f1.map(x => x + 2)
val f3 = f2.flatMap(y => Future { y * 3 })
val result = Await.result(f3, 1.second)
println(result)
}
}Recap: Chaining Async Tasks
You've learned powerful ways to compose Scala Futures:
map: Transforms aFuture's successful result into a new value.flatMap: Chains twoFutures where the result of the first is used to start the second.forcomprehensions: Provide a clean, synchronous-looking syntax forflatMapandmapchains.zip: Combines the results of two independentFutures into a tuple.
These tools are crucial for building responsive and efficient asynchronous applications in Scala!
Questions Fréquemment Posées
La leçon « Composition d’opérations asynchrones » est-elle gratuite ?
Oui — le texte complet de « Composition d’opérations asynchrones » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 3 leçons au total.
Qu'est-ce que j'apprendrai dans « Composition d’opérations asynchrones » ?
Apprenez à enchaîner et à combiner plusieurs `Futures` à l’aide de méthodes telles que `map`, `flatMap` et les compréhensions `for`. Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?
Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 3.
Combien de temps prend la leçon « Composition d’opérations asynchrones » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?
Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Introduction aux Futures et aux Promises
- Composition d’opérations asynchrones
- Gestion des erreurs dans les Futures