Guys how is it possible to save the value returned by a go
block into a variable?
doesn't go just return a channel, so can't you just use def or something?
@abhi18av The question is why do you need that and what do you mean by a "variable"
Ohh, I think I always confused var
and variables
- thanks for this hint @cjsauer š
Iād definitely go with moving the ->
inside the def since itās seems more idiomatic
@jumar, a def
expression to be precise
and why do you want to save the go return value into a global var?
Yup I tried, but it stores the channel not the value it returns
Hmm, good question! Let me give more context here
(defn api [{::keys [endpoint method token]
:or {method :get}}]
(->
(go
(<? (fetch/request-async {#_#_::http/url "<https://api.spotify.com/v1/artists/3WrFJ7ztbogyGnTHbHJFl2>"
::http/url (str "<https://api.spotify.com/v1/>" endpoint)
::http/headers {:authorization (str "Bearer " token)}
::http/as ::http/json
::http/method "get"}))
:body)))
Iām trying to only store the value of :body
in the response map in this pathom driven query š@sogaiu, hereās the context
Why do you need async HTTP request execution? Seems to me that you want to block until the response is available and return the data to the client anyway? Moreover, this kind of blocking IO isn't really suitable for go blocks
Iām operating in the cljs
environment with the pathom https://cljdoc.org/d/com.wsscode/pathom/2.2.24/api/com.wsscode.pathom.diplomat.http.fetch
Maybe thereās a better way to get this done :thinking_face:
@abhi18av late reply, but maybe you just need to move your thread ->
inside the go block:
(defn api [{::keys [endpoint method token]
:or {method :get}}]
(go
(->
(<? (fetch/request-async {#_#_::http/url "<https://api.spotify.com/v1/artists/3WrFJ7ztbogyGnTHbHJFl2>"
::http/url (str "<https://api.spotify.com/v1/>" endpoint)
::http/headers {:authorization (str "Bearer " token)}
::http/as ::http/json
::http/method "get"})))
:body))
And then if you really wanted to store this in a var, you would do this:
(go (def result (<! (api ...))))
This is really questionable Clojure thoā¦really only useful while debugging at the REPL.
As an aside, you shouldnāt confuse āvarsā with āvariablesā. They are totally different things. Vars are always top-level, and using def
is not assignment like in other languages. Their fundamental purpose is to hold constant values. This is why the above code snippet comes with big warning signs
ā ļø Only do this while debugging at the REPL ā ļø