/
user.cljs
101 lines (80 loc) · 2.44 KB
/
user.cljs
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
(ns user
(:require
[kitchen-async.promise :as p]
[town.lilac.async.seq :as aseq]))
;;
;; Example of an async API for fetching pages of data, where the token in the
;; payload tells the consumer how to fetch the next page
;;
(def ^:private pages-data
"Some example page data, keyed by the `:page`.
The next page is contained in the payload at the `:next` key."
(into {} (map (juxt :page identity)) (for [n (range 10)]
{:page n
:next (inc n)})))
(defn- fetch-page
"Fetch a particular page"
[n]
(prn "Fetching " n)
(js/Promise.resolve (get pages-data n)))
(defn simple-example
[]
(let [pages (aseq/iteration fetch-page
:initk 0
:kf :next)]
(-> pages
(aseq/aseq)
(.then aseq/next)
(.then aseq/next)
(.then aseq/first))))
#_(.then (simple-example) prn)
(defn recursive-example
([n]
(let [pages (aseq/iteration fetch-page
:initk 0
:kf :next)]
(.then
(aseq/first pages)
#(recursive-example (dec n) [%] (aseq/next pages)))))
([n results p]
(if (pos? n)
(.then p (fn [aseq]
(if aseq
(.then
(aseq/first aseq)
#(recursive-example
(dec n) (conj results %)
(aseq/next aseq)))
results)))
results)))
#_(.then (recursive-example 4) prn)
(defn transduce-example
[]
(aseq/transduce
(comp (take 3) (map :page))
conj []
(aseq/iteration fetch-page
:initk 0
:kf :next)))
#_(.then (transduce-example) prn)
(defn collect-example
[]
(aseq/collect [] (comp (take 3) (map :page)) (aseq/iteration fetch-page
:initk 0
:kf :next)))
#_(.then (collect-example) prn)
(defn loop-example
[]
(p/loop [pages (aseq/iteration fetch-page
:initk 0
:kf :next)
results []
page-num 6]
(p/let [page (aseq/first pages)]
(if (and (pos? page-num) (some? page))
(p/recur
(aseq/next pages)
(conj results page)
(dec page-num))
results))))
#_(.then (loop-example) prn)