Created
March 27, 2014 15:30
-
-
Save amacdougall/9810205 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Without channels: | |
;; Makes an HTTP request, and executes the callback on the response when it | |
;; comes. This should be familiar from Javascript. | |
(defn get-pudding [callback] | |
(http-get {:url "pudding" | |
:success callback})) | |
(get-pudding (fn [response] (eat response))) | |
;; With channels: | |
;; Makes an HTTP request, and returns an output channel which will receive the | |
;; response when it comes. | |
(defn get-pudding [] | |
(let [out (chan)] | |
(http-get {:url "pudding" | |
:success (fn [response] | |
(go (>! out response)))}))) | |
;; This looks like synchronous code, but actually the go block tells it to wait | |
;; until it's possible to take from the output channel and then eat the result. | |
(go (eat (<! (get-pudding)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment