Fork me on GitHub
#cljsrn
<
2021-04-15
>
hadils01:04:40

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.

Janne Sauvala13:04:48

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 🙂

Aleksander Rendtslev20:04:38

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

Michel A.07:04:50

you could also take a look at some other libraries that help promise use in cljs : https://github.com/athos/kitchen-async

raspasov11:04:27

@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

raspasov11:04:54

Globally call (extend-promises-as-pair-channels!)

raspasov11:04:38

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

pez05:04:01

You might want to ask about that in #clojurescript , @hadilsabbagh18 .