Search code examples
async-awaites6-promiseclojurescript

What is the idiomatic way to implement aWait calls in ClojureScript?


I want to call an asynchronous api in javascript that uses callbacks using a syntax similar to aWait:

try {
   let a = await asyncFunction1("foo");
   let b = await asyncFunction2("bar", a);
   do something ...
}
catch (e) {
   handle errors ...
}

In clojureScript, it could be similar to:

(try 
  (let [a  (await (asyncFunction1 "foo"))
        b  (await (asyncFunction2 "bar" a))]
    do something ...)
  (catch :default e 
   handle errors ... ))

The core.async library seems to be an overkill for this simple code pattern. I found some libraries but they were version 0.1.0-SNAPSHOT. If necessary, I can convert the api calls to return Promises.


Solution

  • Try the promesa library. It uses macros give you almost exactly the syntax you are looking for, and as you suggest, it is not as heavyweight as core.async. (Using promises instead of core.async also has the advantage of handling exceptions much more naturally and with better stack traces.)

    The syntax would be something like this:

    (require '[promesa.core :as p])
    (p/alet
      (-> (p/alet [a  (p/await (asyncFunction1 "foo"))
                   b  (p/await (asyncFunction2 "bar" a))]
           do something ...)
          (catch (fn [error] 
                   handle errors ... ))))