Skip to content

Instantly share code, notes, and snippets.

@alexkehayias
Created February 22, 2015 00:46
Show Gist options
  • Save alexkehayias/f1e81c164e1feb9877f8 to your computer and use it in GitHub Desktop.
Save alexkehayias/f1e81c164e1feb9877f8 to your computer and use it in GitHub Desktop.
Call some function asynchronously, reduce the results, and call the callback with the result
(ns user
(:require [cljs.core.async :refer [chan <! >!]]
[cljs.core.async :as async]
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn async-reduce
"Reduce a value over a collection of functions asynchronously
and merge the results.
Example:
(async-reduce + 0 [inc inc] println)"
[merge-fn init-val fns callback]
(let [work (count fns)
ch (chan work)
counter (chan 1)]
(go (>! counter 0))
(doseq [f fns]
(go (let [c (<! counter)]
(if (= (inc c) work)
(do (close! counter)
(close! ch)
(callback (<! (async/reduce merge-fn init-val ch))))
(do (>! ch (f init-val))
(>! counter (inc c)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment