Mr. Robot
Mr. Robot

Reputation: 1834

How do I make an http request response useful with Clojure?

The response I get when making an http request JavaScript is usually an array of objects after parsing the data. With ClojureScript I get a very complex data structure back after making a request with the cljs-http library. The docs say that it returns a core.async channel, so my first question is how do I parse that in to data I can map over? Here's the top level view of my response:

enter image description here

Here's my code:

(defn getFileTree []
  (def API-URL "x")
  (go (let [response (<! (http/get API-URL
                                   {:with-credentials? false
                                    :headers {"Content-Type" "application/json"}}))]
        (js/console.log (:status response))
        (js/console.log (:body response)))))

My second question is, say if I call the function getFileTree from another namespace like this:

(def res (api/getFileTree))
  (js/console.log res)

and want res to directly resolve to the response of the http request, how do I do that? At the moment it looks like this:

enter image description here

Upvotes: 1

Views: 902

Answers (1)

Victor Basso
Victor Basso

Reputation: 5796

The go block returns a channel. You have a couple options:

1. Read from that channel with <! in another go block

(go (js/console.log (<! api/getFileTree)))

2. Pass a callback with take!

(take! api/getFileTree js/console.log)

You might be tempted to:

3. Block with <!! to get the result in the current thread.

(js/console.log (<!! api/getFileTree))

But this is not available in ClojureScript because javascript is single-threaded so blocking causes the page to hang.

Upvotes: 0

Related Questions