0Pricing
Scala for Backend Engineering & Functional Programming · درس

مقدمة إلى Futures وPromises

افهم المفاهيم الأساسية لـ `Future` للنتائج غير المتزامنة و`Promise` لإكمالها

مقدمة إلى Futures وPromises درس مجاني في Scala for Backend Engineering & Functional Programming على CoddyKit. هذا هو الدرس 1 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Scala for Backend Engineering & Functional Programming، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Scala for Backend Engineering & Functional Programming 3 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Async Code: Why It Matters

In programming, tasks can run synchronously (one after another) or asynchronously (tasks can start without waiting for previous ones to finish).

Asynchronous programming is crucial for building responsive applications that don't freeze while waiting for slow operations like network requests or database queries.

The Problem with Blocking Calls

Imagine your program needs to fetch data from the internet. If this operation is blocking, your program will pause and do nothing else until the data arrives.

This can lead to a 'frozen' user interface or inefficient server-side applications. We need a way to perform these tasks in the background without halting the main flow.

Introducing Scala Futures

Scala's Future is a powerful tool for asynchronous programming. It represents a value that may not yet be available, but will be at some point in the future.

  • Think of it like ordering a coffee: you get a receipt (the Future) and can do other things while your coffee is being made.
  • When the coffee is ready, the receipt is 'completed' with your drink (the result).

Creating Your First Future

You can create a Future by wrapping a computation in Future { ... }. This computation will run on a separate thread.

An ExecutionContext is needed to schedule these tasks. We'll use a global one for simplicity.

import scala.concurrent.{Future, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

object Main extends App {
  println("Starting computation...")

  val f: Future[Int] = Future {
    Thread.sleep(1000) // Simulate a long operation
    42
  }

  f.onComplete {
    case Success(value) => println(s"Result: $value")
    case Failure(e) => println(s"Error: ${e.getMessage}")
  }

  println("Computation started, continuing...")
  // Keep main thread alive for a bit to see Future's result
  Thread.sleep(2000)
}

Understanding ExecutionContext

An ExecutionContext is essentially a thread pool where asynchronous computations are run.

  • It manages how and when tasks are executed.
  • For quick examples, scala.concurrent.ExecutionContext.Implicits.global is often used, providing a default thread pool.
  • In real applications, you might configure specific thread pools for better control over resource usage.

Handling Future Results: onComplete

The onComplete method is used to define what happens when a Future finishes, whether it succeeds or fails.

It takes a function that operates on a scala.util.Try, which can be either Success(value) or Failure(exception).

import scala.concurrent.{Future, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

object Main extends App {
  val futureSuccess = Future { 10 / 2 }
  val futureFailure = Future { 10 / 0 }

  futureSuccess.onComplete {
    case Success(result) => println(s"Success: $result")
    case Failure(e) => println(s"Error: ${e.getMessage}")
  }

  futureFailure.onComplete {
    case Success(result) => println(s"Success: $result")
    case Failure(e) => println(s"Error: ${e.getMessage}")
  }

  Thread.sleep(100) // Allow Futures to complete and print
}

Simplified Handlers: Success/Failure

For simpler cases, you can use onSuccess and onFailure to handle only successful results or only errors, respectively.

  • onSuccess takes a function for the successful value.
  • onFailure takes a function for the exception.
  • These are convenience methods built on top of onComplete.
import scala.concurrent.{Future, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global

object Main extends App {
  val futureValue = Future { "Hello, Scala!" }

  futureValue.onSuccess { case msg => println(s"Got message: $msg") }
  futureValue.onFailure { case e => println(s"Oops, an error: ${e.getMessage}") }

  val futureError = Future { throw new RuntimeException("Something broke!") }

  futureError.onSuccess { case msg => println(s"Got message: $msg") }
  futureError.onFailure { case e => println(s"Oops, an error: ${e.getMessage}") }

  Thread.sleep(100) // Allow Futures to complete and print
}

What is a Scala Promise?

While a Future is a read-only placeholder for a result, a Promise is a write-once container that can be completed with a value or an exception.

  • A Promise is used to complete a Future.
  • You create a Promise, get its associated Future, and then complete the Promise when the result is ready.

Fulfilling a Promise

You can complete a Promise using its success() or failure() methods. Once a Promise is completed, its associated Future will also complete.

Attempting to complete a Promise more than once will result in an error.

import scala.concurrent.{Future, Promise, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

object Main extends App {
  val p = Promise[String]() // Create a Promise that will hold a String
  val f: Future[String] = p.future // Get the Future associated with the Promise

  f.onComplete {
    case Success(value) => println(s"Future completed with: '$value'")
    case Failure(e) => println(s"Future failed with: ${e.getMessage}")
  }

  // Simulate an async operation completing the promise
  Future {
    Thread.sleep(500)
    p.success("Data fetched successfully!") // Complete the Promise
  }

  println("Promise created, waiting for completion...")
  Thread.sleep(1000) // Keep main thread alive to see Future's result
}

Futures and Promises Together

Future and Promise often work hand-in-hand. A common pattern is to use a Promise when you need to manually control the completion of a Future, perhaps from an external system or an older, callback-based API.

This allows you to wrap non-Future-based asynchronous operations into the Future model, making them compatible with Future-based code.

import scala.concurrent.{Future, Promise, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

object Main extends App {
  def performLongTask(data: String): Future[String] = {
    val p = Promise[String]()
    // Simulate an external system or callback-based API
    Future {
      Thread.sleep(700)
      if (data == "fail") p.failure(new Exception("Task failed!"))
      else p.success(s"Processed: $data")
    }
    p.future // Return the Future that will be completed by the Promise
  }

  val task1 = performLongTask("input data")
  task1.onComplete { case Success(res) => println(s"Task 1: $res") case Failure(e) => println(s"Task 1: ${e.getMessage}") }

  val task2 = performLongTask("fail")
  task2.onComplete { case Success(res) => println(s"Task 2: $res") case Failure(e) => println(s"Task 2: ${e.getMessage}") }

  Thread.sleep(1500) // Keep main thread alive for results
}

Quick Check: Future vs. Promise

Which of the following statements correctly describe the roles of Future and Promise in Scala?

Recap: Futures & Promises

Great job! In this lesson, you've learned the fundamentals of asynchronous programming in Scala:

  • Future: A placeholder for a result that will eventually be available.
  • Promise: A write-once container used to manually complete a Future.
  • ExecutionContext: Schedules the execution of asynchronous tasks.
  • How to handle Future results using onComplete, onSuccess, and onFailure.

These concepts are building blocks for more complex asynchronous patterns!

الأسئلة الشائعة

هل درس «مقدمة إلى Futures وPromises» مجاني؟

نعم — نص درس «مقدمة إلى Futures وPromises» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Scala for Backend Engineering & Functional Programming، انتقل إلى CoddyKit PRO. تتضمن دورة Scala for Backend Engineering & Functional Programming 3 دروس في المجموع.

ماذا ستتعلم في «مقدمة إلى Futures وPromises»؟

افهم المفاهيم الأساسية لـ `Future` للنتائج غير المتزامنة و`Promise` لإكمالها تتمرن على Scala for Backend Engineering & Functional Programming مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Scala for Backend Engineering & Functional Programming؟

لا تُشترط خبرة سابقة. Scala for Backend Engineering & Functional Programming على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 3.

كم من الوقت يستغرق درس «مقدمة إلى Futures وPromises»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Scala for Backend Engineering & Functional Programming هذا؟

نعم. كل درس في Scala for Backend Engineering & Functional Programming يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. مقدمة إلى Futures وPromises
  2. تركيب العمليات غير المتزامنة
  3. معالجة الأخطاء في Futures
← العودة إلى Scala for Backend Engineering & Functional Programming