/
async_cljs.clj
71 lines (60 loc) · 1.66 KB
/
async_cljs.clj
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
61
62
63
64
65
66
67
68
69
70
71
(ns com.wsscode.common.async-cljs
"DEPRECATED: please use com.wsscode.async.async-cljs instead"
(:require
[cljs.core.async :as async]))
(defmacro if-cljs
[then else]
(if (:ns &env) then else))
(defmacro go-catch [& body]
`(async/go
(try
~@body
(catch :default e# e#))))
(defmacro <!p [promise]
`(consumer-pair (cljs.core.async/<! (promise->chan ~promise))))
(defmacro <? [ch]
`(throw-err (cljs.core.async/<! ~ch)))
(defmacro <?maybe
"Tries to await for a value, first if checks if x is a channel, if so will read
on it; then it checks if it's a JS promise, if so will convert it to a channel
and read from it. Otherwise returns x as is."
[x]
`(let [res# ~x]
(cond
(chan? res#)
(<? res#)
(promise? res#)
(<!p res#)
:else
res#)))
(defmacro <!maybe [x]
`(let [res# ~x]
(if (chan? res#) (cljs.core.async/<! res#) res#)))
(defmacro let-chan
"Handles a possible channel on value."
[[name value] & body]
`(let [res# ~value]
(if (chan? res#)
(go-catch
(let [~name (<? res#)]
~@body))
(let [~name res#]
~@body))))
(defmacro let-chan*
"Like let-chan, but async errors will be returned instead of propagated"
[[name value] & body]
`(let [res# ~value]
(if (chan? res#)
(go-catch
(let [~name (cljs.core.async/<! res#)]
~@body))
(let [~name res#]
~@body))))
(defmacro go-promise [& body]
`(let [ch# (cljs.core.async/promise-chan)]
(async/go
(let [res# (try
~@body
(catch :default e# e#))]
(cljs.core.async/put! ch# res#)))
ch#))