0Pricing
Clojure Functional Programming & JVM Backend Development · Lekcja

Promises, Futures i operacje asynchroniczne

Poznaj wzorce programowania asynchronicznego w Clojure, które pomagają obsługiwać długotrwałe zadania i nieblokujące operacje wejścia-wyjścia.

Promises, Futures i operacje asynchroniczne to bezpłatna lekcja Clojure Functional Programming & JVM Backend Development na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Clojure Functional Programming & JVM Backend Development, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Clojure Functional Programming & JVM Backend Development zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Intro to Asynchronous Programming

Welcome! In this lesson, we'll explore asynchronous programming in Clojure. This is key for building responsive applications that don't freeze while waiting for long tasks.

Asynchronous tasks run in the 'background', allowing your main program to continue without interruption. When the background task finishes, it delivers its result.

Blocking vs. Non-Blocking

Imagine fetching data from a slow server. A blocking operation would make your application wait until the data arrives. During this time, nothing else can happen.

A non-blocking operation starts the fetch but immediately returns control to your application. Your app can then do other things, and process the data once it's available.

Clojure's 'future' Macro

Clojure provides the future macro to run a computation on a separate thread. This makes the computation asynchronous and non-blocking from the caller's perspective.

The future immediately returns a 'future' object, which is a placeholder for the eventual result.

Using 'future' for Async Tasks

Let's see future in action. We'll simulate a long-running task using Thread/sleep. Notice how the "Future started" message appears instantly.

(ns my-app.core
  (:gen-class))

(defn -main
  "Demonstrates a simple future."
  [& args]
  (println "Main thread: Starting future...")
  (let [f (future
            (println "  Future thread: Working...")
            (Thread/sleep 2000) ; Simulate work
            (println "  Future thread: Done!")
            "Result from Future")]
    (println "Main thread: Future started, continuing...")
    ; We'll learn how to get the result next!
    (Thread/sleep 1000) ; Let main thread do other work
    (println "Main thread: End of main.")))

Getting Results from 'future'

To get the actual value from a future, you dereference it. You can use the @ reader macro or the deref function.

If the future's computation isn't finished yet, dereferencing will block the current thread until the result is ready.

(ns my-app.core
  (:gen-class))

(defn -main
  "Dereferencing a future."
  [& args]
  (println "Main thread: Starting future...")
  (let [f (future
            (println "  Future thread: Working...")
            (Thread/sleep 2000)
            "Long Task Complete")]
    (println "Main thread: Future launched.")
    (println "Main thread: Doing other work...")
    (Thread/sleep 500)
    (println "Main thread: Now waiting for future result...")
    (let [result @f] ; Dereference the future
      (println "Main thread: Future result:" result))
    (println "Main thread: All done!")))

Clojure's 'promise' Function

While future runs a computation, a promise is a placeholder for a value that will be delivered later, usually by another thread or an external event.

Think of it as an empty box that someone else will fill. You can wait for the box to be filled by dereferencing it.

Delivering and Dereferencing a Promise

The deliver function is used to put a value into a promise. Once a promise is delivered, its value cannot be changed.

Dereferencing a promise works just like a future: it will block until a value is delivered.

(ns my-app.core
  (:gen-class))

(defn -main
  "Delivering and dereferencing a promise."
  [& args]
  (let [p (promise)]
    (println "Main thread: Created a promise.")
    (future
      (println "  Future thread: Doing async work...")
      (Thread/sleep 1500)
      (let [val "Value from Future!"]
        (println "  Future thread: Delivering value to promise.")
        (deliver p val)))
    (println "Main thread: Waiting for promise to be delivered...")
    (let [result @p] ; Blocks until 'deliver' is called
      (println "Main thread: Promise received:" result))
    (println "Main thread: Program finished.")))

Future and Promise Together

future and promise often work together. A future might perform a complex calculation, and then deliver its result to a promise, which can then be picked up by another part of your application.

This pattern is useful for coordinating between different asynchronous tasks or threads.

(ns my-app.core
  (:gen-class))

(defn long-calculation []
  (println "  Calculation: Starting...")
  (Thread/sleep 2500) ; Simulate heavy work
  (println "  Calculation: Finished.")
  (* 123 456))

(defn -main
  "Coordinating with future and promise."
  [& args]
  (let [calc-promise (promise)]
    (println "Main: Kicking off calculation...")
    (future ; Run calculation in a separate thread
      (let [result (long-calculation)]
        (deliver calc-promise result)))
    (println "Main: Calculation started. Doing other things...")
    (Thread/sleep 1000)
    (println "Main: Still doing other things...")
    (println "Main: Waiting for calculation result...")
    (let [final-result @calc-promise]
      (println "Main: Received final result:" final-result))
    (println "Main: Done.")))

Error Handling with Async Tasks

When an exception occurs inside a future or before a promise is delivered, dereferencing the future/promise will re-throw that exception on the dereferencing thread.

This allows you to handle errors in your main thread, even if they originate from an asynchronous task.

Quick Check: Async Behavior

Consider the following Clojure code snippet:

(let [f (future (Thread/sleep 1000) "Async Result")]
  (println "Started")
  (Thread/sleep 500)
  (println "Waiting...")
  (let [result @f]
    (println "Got:" result)))

What is the *minimum* total time before "Got: Async Result" is printed?

Recap: Promises, Futures & Async

  • Asynchronous programming allows tasks to run without blocking the main program flow.
  • Clojure's future macro runs a computation on a separate thread, returning a placeholder immediately.
  • The promise function creates a placeholder that can be delivered a value later, often from another thread or external source.
  • Both future and promise are dereferenced (using @ or deref) to retrieve their values, blocking if the value isn't ready.
  • Exceptions in async tasks are re-thrown when dereferenced.

Często zadawane pytania

Czy lekcja „Promises, Futures i operacje asynchroniczne” jest bezpłatna?

Tak — pełny tekst „Promises, Futures i operacje asynchroniczne” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Clojure Functional Programming & JVM Backend Development, przejdź na CoddyKit PRO. Kurs Clojure Functional Programming & JVM Backend Development zawiera 4 lekcji w sumie.

Co nauczysz się w „Promises, Futures i operacje asynchroniczne”?

Poznaj wzorce programowania asynchronicznego w Clojure, które pomagają obsługiwać długotrwałe zadania i nieblokujące operacje wejścia-wyjścia. Ćwiczysz Clojure Functional Programming & JVM Backend Development z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Clojure Functional Programming & JVM Backend Development?

Nie wymagamy żadnego doświadczenia. Clojure Functional Programming & JVM Backend Development w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Promises, Futures i operacje asynchroniczne”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Clojure Functional Programming & JVM Backend Development?

Tak. Każda lekcja Clojure Functional Programming & JVM Backend Development zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Refs, Agents i Atoms do zarządzania stanem
  2. Transakcyjna pamięć współdzielona (STM)
  3. Promises, Futures i operacje asynchroniczne
  4. Kanały core.async i bloki go
← Powrót do Clojure Functional Programming & JVM Backend Development