Skip to content

Instantly share code, notes, and snippets.

@mpenet
Created November 24, 2012 10:01
Show Gist options
  • Save mpenet/4139088 to your computer and use it in GitHub Desktop.
Save mpenet/4139088 to your computer and use it in GitHub Desktop.
monads! (kind of)
;; Examples based on code in https://github.com/ibdknox/jayq/tree/let-deferred
;; sugar for do-> ajax-m
(let-ajax [a {:url "http://localhost:8000/1.json"
:dataType :json}
b {:dataType :json :url "http://localhost:8000/2.json"}]
(utils/log a)
(utils/log b))
;; sugar for do-> deferred-m
(let-deferred
[a (jq/ajax "http://localhost:8000/1.json")
:let [foo "bar"]
b (jq/ajax "http://localhost:8000/2.json")]
(utils/log a)
(utils/log b)
(utils/log foo))
(do-> jq/deferred-m
[a (jq/ajax "http://localhost:8000/1.json"))
:let [c (js/Date.)]
:when (== a 2)
b (jq/ajax "http://localhost:8000/2.json")
c (jq/ajax "http://localhost:8000/3.json")]
(concat a b c))
;; definitions
(def deferred-m
{:return $when
:bind (fn [x f]
(let [dfd ($deferred)]
(done x (fn [v]
(done (f v) (partial resolve dfd))))
(promise dfd)))})
(def ajax-m
{:return identity
:bind (fn [x f] (ajax (assoc x :success f)))})
;; generated code for the do-> deferred-m example:
var G__8784 = (new cljs.core.Keyword("\ufdd0'bind")).call(null, jayq.core.deferred_m);
var G__8785 = (new cljs.core.Keyword("\ufdd0'return")).call(null, jayq.core.deferred_m);
G__8784.call(null, jayq.core.ajax.call(null, "http://localhost:8000/1.json"), function(a) {
var c = new Date;
if(a === 2) {
return G__8784.call(null, jayq.core.ajax.call(null, "http://localhost:8000/2.json"), function(b) {
return G__8784.call(null, jayq.core.ajax.call(null, "http://localhost:8000/3.json"), function(c__$1) {
return G__8785.call(null, cljs.core.concat.call(null, a, b, c__$1))
})
})
}else {
return G__8785.call(null, a === 2)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment