Skip to content

Instantly share code, notes, and snippets.

@leonoel
Created December 6, 2018 20:17
Show Gist options
  • Save leonoel/79ac90440584ec518f2acf161996a479 to your computer and use it in GitHub Desktop.
Save leonoel/79ac90440584ec518f2acf161996a479 to your computer and use it in GitHub Desktop.
cloroutine-based async/await
(ns asyncawait
(:refer-clojure :exclude [await])
(:require [cloroutine.core :refer [cr]]))
(defmacro async [& body]
`(js/Promise. (fn [s# f#]
(spawn (cr {await thunk}
(try (s# (do ~@body))
(catch :default e# (f# e#))))))))
(ns asyncawait)
(def ^:dynamic *success*)
(def ^:dynamic *failure*)
(def ^:dynamic *status*)
(def ^:dynamic *result*)
(defn await [p]
(.then p *success* *failure*))
(defn thunk []
(if *status* *result* (throw *result*)))
(defn spawn [c]
(letfn [(run []
(binding [*success* success
*failure* failure]
(c)))
(success [x]
(binding [*status* true
*result* x] (run)))
(failure [x]
(binding [*status* false
*result* x] (run)))]
(run)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment