Skip to content

Instantly share code, notes, and snippets.

@lilactown
Created May 16, 2017 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lilactown/59fedded0ea004f37a9480c2ea80169c to your computer and use it in GitHub Desktop.
Save lilactown/59fedded0ea004f37a9480c2ea80169c to your computer and use it in GitHub Desktop.
A simple macro to aid with dealing with promise chains in ClojureScript
(ns lilactown.promise)
;; This is a simple macro to aid with dealing with promise chains
;; in ClojureScript. Often external JS libraries (such as request-promise
;; or other async libs) return a promise object, so we write code like:
;;
;; (-> promise-value
;; (.then do-something)
;; (.then #(do-something-else %))
;; (.then (fn [val] (and-again val)))
;;
;; With `promise->`, we can remove the .then and use it like any other threading macro:
;;
;; (promise-> promise-value
;; do-something
;; #(do-something-else %)
;; (fn [val] (and-again val)))
(defmacro promise-> [promise & body]
`(-> ~promise
~@(map (fn [expr] (list '.then expr)) body)))
@lilactown
Copy link
Author

lilactown commented May 23, 2017

(defmacro ->-> [value fun & body]
  `(-> ~promise
       ~@(map (fn [expr] (list fun expr)) body)))

(->-> promise-value .then
  do-something
  #(do-something-else %)
  (fn [val] (and-again val)))```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment