Fork me on GitHub
#core-async
<
2019-09-19
>
Abhinav Sharma11:09:37

Guys how is it possible to save the value returned by a go block into a variable?

sogaiu12:09:04

doesn't go just return a channel, so can't you just use def or something?

Abhinav Sharma13:09:03

Yup I tried, but it stores the channel not the value it returns

jumar12:09:42

@abhi18av The question is why do you need that and what do you mean by a "variable"

Abhinav Sharma12:09:27

@U06BE1L6T, a def expression to be precise

jumar13:09:33

and why do you want to save the go return value into a global var?

Abhinav Sharma13:09:47

Hmm, good question! Let me give more context here

(defn api [{::keys [endpoint method token]
            :or    {method :get}}]
  (->
    (go
      (<? (fetch/request-async {#_#_::http/url ""
                                ::http/url     (str "" 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 🙂

Abhinav Sharma13:09:25

@UG1C3AD5Z, here’s the context

jumar13:09:46

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

Abhinav Sharma13:09:16

Maybe there’s a better way to get this done :thinking_face:

cjsauer20:09:05

@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 ""
                               ::http/url     (str "" endpoint)
                               ::http/headers {:authorization (str "Bearer " token)}
                               ::http/as      ::http/json
                               ::http/method  "get"})))
    :body))

cjsauer20:09:24

And then if you really wanted to store this in a var, you would do this: (go (def result (<! (api ...))))

cjsauer20:09:24

This is really questionable Clojure tho…really only useful while debugging at the REPL.

cjsauer21:09:23

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 ⚠️

Abhinav Sharma12:09:39

Ohh, I think I always confused var and variables - thanks for this hint @U6GFE9HS7 😅 I’d definitely go with moving the -> inside the def since it’s seems more idiomatic