I posted an example for fetch
using js-await
here.
Currently only available when using shadow-cljs though.
(defn init []
(js-await [res (js/fetch "/cheshire-cat")]
(js/console.log "res" res)
(js-await [body (.json res)]
(js/console.log "got some json" body))))
fetch
returns a Promise which will provide the async result. You cannot access the result in a sync fashion. So, with your raw example maybe gets a bit cleaner with fn
instead of #()
. body
is the JSON object result. You can only access it there, not from the init
function that called all this.
(defn ^:export init []
(-> (js/fetch "/cheshire-cat")
(.then (fn [response]
(-> (.json response)
(.then (fn [body]
(js/console.log body)
)))))))
With promise chaining this could be written as
(defn ^:export init []
(-> (js/fetch "/cheshire-cat")
(.then #(.json %))
(.then (fn [body]
(js/console.log body)
))))