-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.clj
69 lines (57 loc) · 1.76 KB
/
core.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
(ns conquerant.core
(:refer-clojure :exclude [await promise])
(:require [clojure.walk :refer [prewalk-replace]]
[conquerant.internals :as ci]))
(defn- async-fn [fn]
(for [[argv & body] (rest fn)]
(list argv (cons `ci/ado body))))
(defmacro async
"If `expr` is a `fn` or `defn` form, its body will
run asyncronously. Otherwise, `expr` will itself
run asyncronously, and return a `CompletableFuture`.
All async exectution occurs on the `ci/*executor*` pool,
which is bound to the common ForkJoinPool by default."
[expr]
(if (and (coll? expr) (seq expr))
(let [expr (->> expr
(prewalk-replace {'let* `ci/alet
'let `ci/alet
`let `ci/alet
`await 'await})
macroexpand)
type (first expr)]
(cond
(or (= 'fn* type)
(= `fn type))
`(fn ~@(async-fn expr))
(= `def type)
`(defn ~(second expr)
~@(async-fn (last expr)))
(= `do type)
`(ci/ado ~(rest expr))
:else
`(ci/ado ~expr)))
`(ci/ado ~expr)))
(defn await
"Use inside `async` `let` blocks:
(async
(let [x (async :x)
y (await x)]
y))
Will wait for the `CompletableFuture` to complete
before evaluation resumes."
[v]
(throw (Exception. "await used outside async let block!")))
(defmacro promise
"Used to get values out of callbacks.
ex:
;; some fn that takes a callback
(defn fetch [url callback] ...)
;; can be used as
(let p
(promise [res rej]
(fetch \"http://some.service.com\"
#(res %))))"
[[resolve reject] & body]
`(ci/promise* (fn [~resolve ~reject]
~@body)))