พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส
สำรวจรูปแบบการเขียนโปรแกรมแบบอะซิงโครนัสใน Clojure เพื่อจัดการงานที่ใช้เวลานานและการรับส่งข้อมูลเข้าออกแบบไม่บล็อก
พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส เป็นบทเรียน Clojure Functional Programming & JVM Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Clojure Functional Programming & JVM Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Clojure Functional Programming & JVM Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
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
futuremacro runs a computation on a separate thread, returning a placeholder immediately. - The
promisefunction creates a placeholder that can bedelivered a value later, often from another thread or external source. - Both
futureandpromiseare dereferenced (using@orderef) to retrieve their values, blocking if the value isn't ready. - Exceptions in async tasks are re-thrown when dereferenced.
คำถามที่พบบ่อย
บทเรียน “พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clojure Functional Programming & JVM Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clojure Functional Programming & JVM Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส”
สำรวจรูปแบบการเขียนโปรแกรมแบบอะซิงโครนัสใน Clojure เพื่อจัดการงานที่ใช้เวลานานและการรับส่งข้อมูลเข้าออกแบบไม่บล็อก คุณปฏิบัติ Clojure Functional Programming & JVM Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clojure Functional Programming & JVM Backend Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clojure Functional Programming & JVM Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Clojure Functional Programming & JVM Backend Development นี้ได้ไหม
ได้ บทเรียน Clojure Functional Programming & JVM Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- รีฟ เอเจนต์ และอะตอมสำหรับจัดการสถานะ
- หน่วยความจำธุรกรรมซอฟต์แวร์ (STM)
- พรอมิส ฟิวเจอร์ และการดำเนินการแบบอะซิงโครนัส
- Channel และบล็อก Go ของ core.async