Created
July 14, 2015 01:14
-
-
Save bostonou/685d946a1e92935461c7 to your computer and use it in GitHub Desktop.
Promise.all with core.async
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 cljs-made-easy.core | |
(:refer-clojure :exclude [into]) | |
(:require-macros [cljs.core.async.macros :refer [go go-loop]]) | |
(:require [cljs.core.async :refer [<! >!] :as a])) | |
(enable-console-print!) | |
(defn resolving-promise [key t reject] | |
(go | |
(pr (str key " starting")) | |
(<! (a/timeout t)) | |
(pr (str key " finished")) | |
(str key " waited " t "ms"))) | |
(defn rejecting-promise [key t reject] | |
(go | |
(pr (str key " starting")) | |
(<! (a/timeout t)) | |
(>! reject (str key " had an error after " t "ms")) | |
"This string won't be used")) | |
(defn into [coll & chans] | |
(go-loop [coll coll | |
chans chans] | |
(if (seq chans) | |
(recur (conj coll (<! (first chans))) | |
(rest chans)) | |
coll))) | |
(defn all [reject & chans] | |
(go | |
(let [all-chans (apply into [] chans) | |
[v ch] (a/alts! [reject all-chans])] | |
(if (= ch reject) | |
(pr (str "Rejected value: " v)) | |
(pr (str "Resolved values: " v)))))) | |
(defn demo-resolving [] | |
(let [reject (a/chan)] | |
(go | |
(<! (all reject | |
(resolving-promise :c1 2000 reject) | |
(resolving-promise :c2 1000 reject) | |
(resolving-promise :c3 1500 reject)))) | |
nil)) | |
(defn demo-rejecting [] | |
(let [reject (a/chan)] | |
(go | |
(<! (all reject | |
(resolving-promise :c1 2000 reject) | |
(resolving-promise :c2 1000 reject) | |
(rejecting-promise :c3 1500 reject)))) | |
nil)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment