Hi folks:
I'm trying to do some http call in clojure using fetch. I'm just trying to debug and see the output but all I got is a #<Promise[~]> when running REPL.
How can I deref this and see the data?
(p/let [response (go (<! (fetch/get request-url {:headers {:x-v 1}})))]
(:body response))Since you're already using Promesa you can simplify/fix your code like this (assuming fetch/get is returning a js promise):
(p/let [response (fetch/get request-url {:headers {:x-v 1}})]
(:body response))
If you want to continue to use core.async, you could use the new-ish <p! macro.
https://clojurescript.org/guides/promise-interop#using-promises-with-core-async
(go
(<p! (fetch/get request-url {:headers {:x-v 1}})))
Which you can require like this:
[cljs.core.async.interop :refer-macros [<p!]]
You can then change your code to just use let instead of p/let.
Like other posters I think core.async adds too much complexity for a use-case like this. I would personally use promesa, but another option if you don't want that dependency is using js-await which is available in shadow-cljs and nbb but unfortunately not in core cljs.I usually suggest people to stop using core.async and Promesa when they can be avoided. More problems that it's worth IMO.
(-> (fetch/get ...)
(.then (fn [response]
(let [body (:body response)]
... do whatever you want to the `body` ...))))
If you want to see the value of body right in the REPL, just create some atom and reset! it in that let, and after the data is fetched just deref the atom in the REPL.> js-await which is available in shadow-cljs and nbb but unfortunately not in core cljs.
Correction: I just realized I was spreading fake news saying js-await is in nbb. It's in squint not nbb. Sorry about that!
Thanks folks!
I was able to see the content of my request, which lead me to another issue .
{:error #object[SyntaxError SyntaxError: Unexpected end of JSON input]}
Which is kinda crazy because the url works on curl and Postman, and I tried another one and it worked. So pretty much the get request works but in the fetch call.
I saw in curl that the json came with a % at the end. Don't know if it's curl itself or something wrong in the call that makes json looks weird and postman somehow fix it.
The % could be added by your shell to denote that the output had no newline at the end.
I found the issue. It missed me to add :content-type :json to the header request.
Thanks everyone for help!
You cannot "deref" (block until completion) on a js promise like that
p/let returns a promise. You simply cannot have the content of a promise as the REPL output. You have to explicitly call (println ...) on it.
Oh sorry, quite right. I misread that.