Last active
September 25, 2017 14:20
-
-
Save darwin/a667a13cd30eec5cafa4e695bd00cc79 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
(ns promise-test.core | |
(:require-macros [cljs.core.async.macros :refer [go]]) | |
(:require [cljs.core.async :refer [<! timeout chan put!]])) | |
(def delay-ms 100) | |
(defn async [n & [f]] | |
(go | |
(<! (timeout delay-ms)) | |
((or f identity) n))) | |
(defn square [n] | |
(* n n)) | |
(defn serial [x] | |
(go | |
(let [n (<! (async x)) | |
n-squared (<! (async x square))] | |
(+ n n-squared)))) | |
(defn parallel [x] | |
(go | |
(let [n-chan (async x) | |
n-squared-chan (async x square) | |
[n n-squared] (<! (cljs.core.async/map vector [n-chan n-squared-chan]))] | |
(+ n n-squared)))) | |
;; helpers for working with promises in CLJS | |
(defn soon | |
"Simulate an asynchronous result" | |
([v] (soon v identity)) | |
([v f] (js/Promise. (fn [resolve] | |
(js/setTimeout #(resolve (f v)) | |
delay-ms))))) | |
(defn promise-to-chan [promise] | |
(let [channel (chan)] | |
(.then promise #(put! channel %)) | |
channel)) | |
(defn serial2 [x] | |
(go | |
(let [n (<! (promise-to-chan (soon x))) | |
n-squared (<! (promise-to-chan (soon x square)))] | |
(+ n n-squared)))) | |
(defn parallel2 [x] | |
(go | |
(let [n-chan (promise-to-chan (soon x)) | |
n-squared-chan (promise-to-chan (soon x square)) | |
[n n-squared] (<! (cljs.core.async/map vector [n-chan n-squared-chan]))] | |
(+ n n-squared)))) | |
(go | |
(js/console.time "serial") | |
(js.console.log "serial:" (<! (serial 5))) | |
(js/console.timeEnd "serial") ; => ~200ms | |
(js/console.time "parallel") | |
(js.console.log "parallel:" (<! (parallel 5))) | |
(js/console.timeEnd "parallel") ; => ~100ms | |
(js/console.time "serial2") | |
(js.console.log "serial2:" (<! (serial2 5))) | |
(js/console.timeEnd "serial2") ; => ~200ms | |
(js/console.time "parallel2") | |
(js.console.log "parallel2:" (<! (parallel2 5))) | |
(js/console.timeEnd "parallel2")) ; => ~100ms |
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
serial: 30 | |
serial: 205.43798828125ms | |
parallel: 30 | |
parallel: 104.713134765625ms | |
serial2: 30 | |
serial2: 202.990966796875ms | |
parallel2: 30 | |
parallel2: 104.5888671875ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment