How do you do JS async/await
in CLJS? I know about core.async
and have experience with it, but I have a very difficult time getting a vallue out of a Promise or an async channel (since they all need to be wrapped in go
blocks). I am still quite new to CLJS so I appreciate any help offered.
Hi, could this help: https://clojurescript.org/guides/promise-interop#using-promises-with-core-async It was new to me that we could use core.async for this. I have just used JS interop to handle promises 🙂
Remember not to try to do it in your render function. Once the promise resolves you want to call a function/hook or the like that updates you state
you could also take a look at some other libraries that help promise use in cljs : https://github.com/athos/kitchen-async
@hadilsabbagh18 I use core-async; Been using this approach for many years, hasn’t caused any issues: https://github.com/raspasov/alexandria-clj/blob/main/src/ss/cljs/promises.cljs (that’s all the code it takes) It’s literally copied from this library (mainly copied to avoid some outdated deps, etc since the library is not maintained atm) https://github.com/jamesmacaulay/cljs-promises/blob/master/src/cljs_promises/async.cljs
Globally call (extend-promises-as-pair-channels!)
And then you can do anywhere:
(a/go
(let [[?value ?error] (<! (js/Promise.resolve 42))]
(println "?value" ?value)
(println "?error" ?error)))
;=>
; ?value 42
; ?error nil
You might want to ask about that in #clojurescript , @hadilsabbagh18 .