Fork me on GitHub

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


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.


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?


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.


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.


No problem! If you want to know more about the JS event loop, I’d recommend this video Imo the speaker explains it very well!


You can do this:

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