Skip to content

Instantly share code, notes, and snippets.

@finalfantasia
Last active March 27, 2025 05:13
Show Gist options
  • Save finalfantasia/e81a8fe812943edbc4b4392143fcff20 to your computer and use it in GitHub Desktop.
Save finalfantasia/e81a8fe812943edbc4b4392143fcff20 to your computer and use it in GitHub Desktop.
Schedule Jobs in Sequence with Promise in ClojureScript
(do
(defn schedule-jobs-in-sequence
"Schedules async `jobs` in sequence by using a JavaScript Promise chain."
[jobs]
(js/Promise.
(fn [resolve reject]
(let [init 42
results (atom [])]
(loop [promise (.resolve js/Promise init)
[job & more] jobs]
(if job
(recur (.then promise (fn [result]
(when (not= result init)
(swap! results conj result))
(job result)))
more)
(-> promise
(.then (fn [result]
(swap! results conj result)
(resolve @results)))
(.catch (fn [error]
(reject error))))))))))
(defn make-job
[n timeout]
(fn [v]
(js/Promise.
(fn [resolve reject]
(js/setTimeout (fn []
(.log js/console "v:" v "job:" n)
(resolve n))
timeout)))))
(-> (schedule-jobs-in-sequence
(for [n (range 10)]
(make-job n (* (rand-int n) 1000))))
(.then (fn [results]
(.log js/console "results:" (clj->js results))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment