Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Promise.all with core.async
(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