/
async_cljs.cljc
60 lines (49 loc) · 1.28 KB
/
async_cljs.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
(ns com.wsscode.common.async-cljs
#?(:cljs (:require-macros [com.wsscode.common.async-cljs]))
(:require [cljs.core.async :as async]
[clojure.core.async.impl.protocols :as async.prot]))
(defmacro if-cljs
[then else]
(if (:ns &env) then else))
(defn chan? [c]
(satisfies? async.prot/ReadPort c))
(defmacro go-catch [& body]
`(async/go
(try
~@body
(catch :default e# e#))))
#?(:cljs
(defn promise->chan [p]
(let [c (async/promise-chan)]
(.then p
#(async/put! c {:success %})
#(async/put! c {:error %}))
c)))
#?(:cljs
(defn consumer-pair [resp]
(if (contains? resp :error)
(throw (:error resp))
(:success resp))))
(defmacro <!p [promise]
`(consumer-pair (async/<! (promise->chan ~promise))))
(defn error? [err]
#?(:clj (instance? Throwable err)
:cljs (instance? js/Error err)))
(defn throw-err [x]
(if (error? x)
(throw x)
x))
(defmacro <? [ch]
`(throw-err (async/<! ~ch)))
(defmacro <?maybe [x]
`(let [res# ~x]
(if (chan? res#) (<? res#) res#)))
(defmacro let-chan
"Handles a possible channel on value."
[[name value] & body]
`(let [~name ~value]
(if (chan? ~name)
(go-catch
(let [~name (<? ~name)]
~@body))
(do ~@body))))