Fork me on GitHub
#clojurescript
<
2022-06-11
>
tianshu09:06:48

When using cljs.async, how to wait until the async code finished?

sansarip17:06:34

Short answer is, you can’t really 🙅 This goes for JS as well; blocking operations go against the single-threaded nature of the runtime. Instead, you should make the async code, once it has completed its task(s), call back to the thing that needs to know that it finished in whatever way best fits your circumstances.

brendnz23:06:12

Please excuse my lack of basic knowledge, but if a person wants to wait for a process to complete, why would they use async in the first place? Why not synchronous code? Does js and clojurescript have synchronous code?

sansarip03:06:43

Sure, the lines of code you write in cljs/js will be executed synchronously and in order unless stated otherwise. If your main thread does not need to do other things while waiting (i.e. if you’re not using JS for a UI), then this strategy may be sufficient! I think I may have over-assumed in my answer. Op may have just been asking if there was an equivalent to <!! , i.e. a way to block while waiting for a message on a channel in cljs, and to that the answer is no.

brendnz03:06:01

Thank you. I found your first answer very informative, and your second answer equally so. I am very fortunate to have read them, because I have not really understood conversations on blocking until now.

sansarip03:06:40

No problem! If you want to know more about the JS event loop, I’d recommend this video https://www.youtube.com/watch?v=8aGhZQkoFbQ Imo the speaker explains it very well!

didibus04:06:31

You can do this:

(go
  (<p! (async-thing))
  ;; what comes after this will run once the async-thing is completed
  (do-after))

1