Created
August 4, 2019 13:43
-
-
Save johanmynhardt/c015a54e06f86761df0dec7835428c8f to your computer and use it in GitHub Desktop.
ClojureScript HTML5 FetchAPI usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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