Futures and promises in Clojure
A future is an object that represents the result of running a function on a different thread. A promise is an object that represents a value that will be delivered at some point in time.
Futures
Futures are useful for long-running computations, or code that can block main threads. Let's create a function that runs for a relatively long time, as follows:
(defn get-user-accounts [] (Thread/sleep 5000) [{:user "John"}{:user "Debbie"}]) (defn get-recent-purchases [] (Thread/sleep 5000) ["vegetables" "fruits"])
The get-user-accounts
and get-recent-purchases
functions can potentially take a long time, depending on the amount of data. Here, we use Thread/sleep
for five seconds, in order to simulate a long-running process. We can try to use these functions, as follows:
(defn long-process [] (let [users (get-user-accounts) purchases (get-recent-purchases)] {:purchases purchases :users users}))
Our long-process
function relies on data from functions...