Last active
June 15, 2021 12:57
-
-
Save borkdude/e926d02b0d44dde04d74364201172e9b to your computer and use it in GitHub Desktop.
promised-let from Chlorine's repl-tooling
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 promised-let | |
(:require [sci.core :as sci])) | |
(def ^:private promised-let | |
"Async let macro from https://github.com/mauricioszabo/repl-tooling." | |
^:sci/macro | |
(fn [_&form _&env bindings & body] | |
(let [binds (->> bindings (partition-all 2 2) reverse)] | |
(loop [body (cons 'do body) | |
[[var elem] & rest] binds] | |
(if (nil? var) | |
body | |
(recur | |
(list 'plet/then (list 'plet/promise elem) (list 'fn [var] body)) | |
rest)))))) | |
(def ^:private plet-ns {'promise #(.resolve js/Promise %) | |
'then #(.then ^js %1 %2) | |
'catch #(.catch ^js %1 %2) | |
'let promised-let}) | |
(defn sleep [ms] | |
(js/Promise. (fn [resolve] | |
(println "sleeping" ms) | |
(js/setTimeout resolve ms)))) | |
(.then (sci/eval-string "(plet/let [_ (sleep 1000) | |
_ (println \"Calculating numbers\") | |
x (+ 1 2 3) | |
y (+ x 2)] | |
y)" | |
{:namespaces {'user {'sleep sleep | |
'println println} | |
'plet plet-ns}}) | |
#(prn :res %)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment