Skip to content

Instantly share code, notes, and snippets.

@johanmynhardt
Created August 4, 2019 13:43
Show Gist options
  • Save johanmynhardt/c015a54e06f86761df0dec7835428c8f to your computer and use it in GitHub Desktop.
Save johanmynhardt/c015a54e06f86761df0dec7835428c8f to your computer and use it in GitHub Desktop.
ClojureScript HTML5 FetchAPI usage
;; This works easiest using the thread-first macro ( -> )
;; I couldn't get it to work with fetch().then().then()[...].catch() for error handling.
(fn []
(->
(js/fetch "/weather-data.json")
(.then
(fn [resp]
(println "status: " (.-status resp))
(when (= 200 (.-status resp))
(->
(.json resp)
(.then
(fn [json]
(println "got txt: " json)))))))))
;; A more useful examlpe, defining a fetch function, and a handler example following this defn.
(defn fetch-json
[uri handle-json-fn]
(->
(js/fetch uri)
(.then
(fn [resp]
(println "status: " (.-status resp))
(when (= 200 (.-status resp))
(->
(.json resp)
(.then handle-json-fn)))))))
(fetch-json "/weather-data.json"
(fn [json]
(println "this is the json I got: " json)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment