Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure(脚本):同步推理异步操作的宏 上下文_Clojure_Clojurescript - Fatal编程技术网

Clojure(脚本):同步推理异步操作的宏 上下文

Clojure(脚本):同步推理异步操作的宏 上下文,clojure,clojurescript,Clojure,Clojurescript,我在玩ClojureScript,所以Ajax对我的作用如下: (make-ajax-call url data handler); 其中处理程序类似于: (fn [response] .... ) 现在,这意味着当我想说“获取新数据,并更新左侧边栏”之类的话时,我的结尾看起来像: (make-ajax-call "/fetch-new-data" {} update-sidebar!) [1] 现在,我更愿意这样写: (update-sidebar! (make-ajax-call "/

我在玩ClojureScript,所以Ajax对我的作用如下:

(make-ajax-call url data handler);
其中处理程序类似于:

(fn [response] .... )
现在,这意味着当我想说“获取新数据,并更新左侧边栏”之类的话时,我的结尾看起来像:

(make-ajax-call "/fetch-new-data" {} update-sidebar!) [1]
现在,我更愿意这样写:

(update-sidebar! (make-ajax-call "/fetch-new-data" {})) [2]
但它不会工作,因为makeajax调用会立即返回

问题: 有没有办法通过单子或宏来实现这一点?所以[2]被自动重写为[1]?我相信:

  • 由于已改写为[1],因此不会出现性能惩罚[
  • 这对我来说更清楚,因为我可以用同步步骤而不是异步事件来思考

    我怀疑我不是第一个遇到这个问题的人,所以如果这是一个众所周知的问题,那么“Google for problem Foo”形式的答案是完全正确的


谢谢!

宏会在保持Ajax调用异步的同时更改代码的外观。
这是一个简单的模板宏。另一种方法是将调用封装在等待结果的函数中进行ajax调用。虽然这两种方法中的任何一种都可以正常工作,但它们可能看起来有点笨拙并且“不像ajax”。这些好处值得额外的抽象层吗?

使用线程宏怎么样?还不够好吗

(->> update-sidebar! (make-ajax-call "/fetch-new-data" {}))

我们在seesaw的文章中对此有一些粗略的想法。请特别查看名称空间。

自2013年6月28日clojure core.async lib发布以来,您或多或少可以通过以下方式完成:

这里粘贴了代码:

(ns fourclojure.stack
    (require [clojure.core.async :as async :refer :all]))

(defn update-sidebar! [new-data]
  (println "you have updated the sidebar with this data:" new-data))

(defn async-handler [the-channel data-recieved]
  (put! the-channel data-recieved)
  )

(defn make-ajax-call [url data-to-send]
  (let [the-channel (chan)]
    (go   
     (<! (timeout 2000)); wait 2 seconds to response
     (async-handler the-channel (str "return value with this url: " url)))
    the-channel
    )
  )

(update-sidebar! (<!! (make-ajax-call "/fetch-new-data" {})))
(ns fourclojure.stack
(需要[clojure.core.async:as-async:refere:all]))
(defn更新侧栏![新数据]
(println“您已使用此数据更新侧栏:“新数据”)
(defn异步处理程序[接收的通道数据]
(放置!接收到的通道数据)
)
(defn进行ajax调用[要发送的url数据]
(让[频道(陈)]
(去
(
更多信息请访问:
*

*

Hi user1383359!,我的答案(与core.async相关)对您解决这个问题有帮助吗?我尝试过,效果很好。这篇文章特别与core.async和ajax调用相关