我一直看到这个宏Task<Task> wrapperTask = Task.Factory.StartNew(...);
Task actualTask = wrapperTask.Unwrap();
Task.WaitAll(actualTask);
,在swanodette的代码中看起来非常有用:
在此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)))))
只是一点宏糖,扩展成类似的东西 (throw-err(<?
[expr]))。在core.async中<!
的用途与...相同 ES6的收益运营商。如果异步进程将错误写入 它的频道我们会把它转换成例外。
但我无法找到它的定义。它是如何在Clojure {Script}中实现的?
答案 0 :(得分: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
看起来应该抛出错误,但事实并非如此。至少不是每次都这样。)