Created
December 6, 2018 20:17
-
-
Save leonoel/79ac90440584ec518f2acf161996a479 to your computer and use it in GitHub Desktop.
cloroutine-based async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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#)))))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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