簡體   English   中英

Clojurescript異步

[英]Clojurescript async <? macro

我一直看到這個宏<? ,在swanodette的代碼中看起來非常有用:

在這個要點

;; 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}中實現的?

好吧這就是我到目前為止所使用的內容。 可能還有改進的余地。

在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看起來應該拋出錯誤,但事實並非如此。至少不是每次都這樣)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM