【问题标题】:Clojurescript async <? macroClojurescript 异步 <?宏
【发布时间】:2015-11-16 08:10:15
【问题描述】:

我一直在 swanodette 的代码中看到这个宏 &lt;?,看起来非常有用:

在这个gist

;; BOOM!!! we can convert async errors into exceptions
(go (try
      (let [x (<? (run-task (.-readFile fs) "foo.txt" "utf8"))]
        (.log js/console "Success" x))
      (catch js/Error e
        (.log js/console "Oops" e))))

在这篇博文中:

(go (try
      (let [tweets    (<? (get-tweets-for "swannodette"))
            first-url (<? (expand-url (first (parse-urls tweets))))
            response  (<? (http-get first-url))]
        (. js/console (log "Most recent link text:" response)))
      (catch js/Error e
        (. js/console (error "Error with the twitterverse:" e)))))

&lt;? 只是一个宏糖,扩展成类似的东西 (抛出错误(&lt;! [expr]))。在 core.async &lt;! 中的目的与 ES6 的收益操作符。如果异步进程将错误写入 它的通道我们会将其转换为异常。

但我找不到它的定义。 Clojure{Script} 中是如何实现的?

【问题讨论】:

  • 仅供参考:他所有的代码都在 github 上:github.com/swannodette/swannodette.github.com 您要查找的文件:macros.clj & helpers.cljs
  • @Andre 谢谢!我在找那个! (在 github 上搜索 不起作用)

标签: asynchronous clojure macros clojurescript


【解决方案1】:

好的,这就是我目前使用的。可能还有改进的余地。

在 Clojure 中:

(defn throw-err [e]
  (when (instance? Throwable e) (throw e))
  e)

(defmacro <? [ch]
  `(throw-err (<! ~ch)))

在 ClojureScript 中:

(defn error? [x]
  (instance? js/Error x))


(defn throw-err [e]
  (when (error? e) (throw e))
  e)

(defmacro <? [ch]
  `(throw-err (<! ~ch)))

虽然我完全不确定我的解决方案的可读性(throw-err 看起来应该会引发错误,但实际上不会。至少不是每次都这样)。

【讨论】:

  • 工作线程中的异常并不一定会让你知道它们发生了。 Stuart Sierra 有一个很好的 blog post 显示您可以建立的一些设置,以确保您真正看到异步世界中的错误。 “在 JVM 中,当在主线程以外的线程上抛出异常时,没有任何东西可以捕获它,什么也不会发生。线程会默默地死掉。”
  • 有必要
  • 回答我自己的问题,是的,它不能是一个函数,因为
猜你喜欢
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
  • 2012-11-29
  • 1970-01-01
  • 2018-10-26
相关资源
最近更新 更多