在javascript中我可以编写一些代码:
var app_state={"context":"loading"};
$.get("")
.then(function(data){
app_state["data"]=data;
})
.then(change("context", "edit"))
.then(render)
在Clojurescript中,我喜欢以下内容:
(-> @app-state
(assoc :context "loading")
(assoc :data (GET "")) ;;async call
(assoc :context "edit")
(render))
不喜欢:
(defn handler [] ...
(GET "" {:handler handler}
答案 0 :(得分:0)
我将GET函数放在函数async-get
中,该函数返回core.async的通道,该通道最终包含" GET"的结果。操作。然后,我将这些操作包装在core.async go
块
; require core.async in ns declaration
;; (:require-macros [cljs.core.async.macros :refer [go]])
;; (:require [cljs.core.async :refer [chan <! >! put! take!]])
(defn async-get
[url]
(let [ch (chan)]
(GET url {:handler (fn [resp]
(put! ch resp))})
ch))
(go
(doto app-state
(swap! assoc :context "loading")
(swap! assoc :data (<! (async-get "")))
(swap! assoc :context "edit")
(render)))
答案 1 :(得分:0)
这就是我们最终解决它的方式:
(defn fetch-weather [query]
(safe-run
(go
(-> @model
(assoc :text (str "Data for " query))
(assoc :weather
(let [data (<! (GET< (str " http://api" query)))]
{
:temp (- (get-in data ["main" "temp"]) 273.15)
:city query
:country (get-in data ["sys" "country"])
}))
(assoc :context "edit")
(swapm! model))))))
和
(defn swapm! [x y]
(swap! y (fn [xx] x)))
和安全运行是一个尝试抓住它。在最后进行交换确保只有在所有其他操作都正常时才进行。所以这是全有或全无。