After fuddling about with Core.async in Trunk I decided it was time to reach out for some input. It was a good thing I did; I had reached a point where I was mostly poking at the functions I thought I understood in core.async, and wasn't really reading their API.
I posted over on clojureverse and quickly had a response that took me through usage of the
promise-chan function that I was missing. It was what I was needed the whole time. I had misinterpreted somewhat the purpose of CSP and core-async; I was not in the need of building a series of processes that communicated through channels; I just wanted a way out of callback hell and to write code that looked a bit more synchronous.
To save you going back to my wondering in the previous post, here's a before and after:
;; definition ;; use
;; use ;;...
This is a pretty simple example and I wouldn't say that it really demonstrates a need for core.async. In fact, it's quite a bit more complicated as now, to properly use
<articles-get I need the following a) The
<sql function for abstracting the use of channels and the use of the
Ok, fine. But what about this mess of spaghetti? (I don't recommend trying to read this, just look at it and feel sad, perhaps?)
Trunk is a bit of a tricky application in that, as far as I've been able to forsee, we have to store singular words in a separate table as articles. My SQL skills aren't quite high enough to make me feel confident regarding how to link an article's text with a series of words; so I went with the hacky way- when you create an article:
- Store all the words independantly
- Get the ids for all those words
- Create a delimited string of those words' ids
- Store that in the database.
Is this a good idea? It doesn't feel like it. But this is the fastest way I knew at the time (and still...don't...know) and I'm still prototyping.
Now then, back to core async. With the help of the
<sql function which looks like this:
I can do steps 1 through 4 to insert an article in my handler like so:
Simple! Further, I have broken out th functions to be much simpler. Now,
insert-article does just that. I can wrap it in a
go block and it will insert an article, assuming you are giving it the right inputs. I could do that with the original callbacks (it hadn't occurred to me to simplify that side of things yet) but nonetheless, I'm happy about that:
That's it! I hope this holds up for a while as I don't want to refactor again. I've heard people talk about ending up in a bit of a mess with core.async code (and I've also heard that the