Skip to content

Instantly share code, notes, and snippets.

@bostonou
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bostonou/916ca98b56b694ff10fd to your computer and use it in GitHub Desktop.
Save bostonou/916ca98b56b694ff10fd to your computer and use it in GitHub Desktop.
Promise.all with core.async
(ns cljs-made-easy.core
(:require-macros [cljs.core.async.macros :refer [go go-loop]])
(:require [cljs.core.async :refer [<! >!] :as a]))
(enable-console-print!)
(defn good-go-block [k t ctrl]
(go
(<! (a/timeout t))
(str k " waited " t "ms")))
(defn bad-go-block [k t ctrl]
(go
(<! (a/timeout t))
(>! ctrl (str k " had an error after " t "ms"))))
(defn ordered-merge [& chans]
(let [out (a/chan (count chans))]
(go-loop [chans chans]
(if (seq chans)
(do
(>! out (<! (first chans)))
(recur (rest chans)))
(a/close! out)))
out))
(defn chan-all []
(go
(let [ctrl (a/chan)
chans [(good-go-block :c1 3000 ctrl)
(good-go-block :c2 1000 ctrl)
(good-go-block :c3 2000 ctrl)
;;uncomment to cause an error and return
;;without waiting for others
#_(bad-go-block :c4 2000 ctrl)
]
all (a/into [] (apply ordered-merge chans))
[v ch] (a/alts! [ctrl all])]
(if (= ch ctrl)
(pr (str "Error: " v "; returning"))
(pr (str "Valid: " v))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment