使用core.async频道在clojure中使用http-kit的帖子结果是否合理?

gil*_*aso 9 clojure core.async http-kit

我是clojure的新手,我正在编写一个库,将发布结果发送到服务器以获得响应.我通过将响应放在core.async通道上来消耗响应.这是理智还是有更好的方法?

以下是我正在做的事情的高级概述:

(defn my-post-request [channel options]
  (client/post http://www.example.com options
          (fn [{:keys [status headers body error]}] ;; asynchronous handle response
              (go (>! channel body)))))

(defn request-caller [options]
  (let [channel (chan)]
    (my-post-request channel options)
    (json/parse-string (<!! (go (<! channel))))))
Run Code Online (Sandbox Code Playgroud)

以下是我使用的实际代码:https://github.com/gilmaso/btc-trading/blob/master/src/btc_trading/btc_china.clj#L63

它有效,但我很难确认这是否是正确的方法.

Bey*_*mor 10

core.async是强大的,但在协调更复杂的异步性时它真的很棒.如果你总是想阻止响应,我建议使用一个,promise因为它有点简单:

(defn my-post-request [result options]
  (client/post http://www.example.com options
          (fn [{:keys [status headers body error]}] ;; asynchronous handle response
              (deliver result body))))

(defn request-caller [options]
  (let [result (promise)]
    (my-post-request result options)
    ; blocks, waiting for the promise to be delivered
    (json/parse-string @result)))
Run Code Online (Sandbox Code Playgroud)

如果您确实想使用通道,可以稍微清理代码.重要的是,您不需要将所有内容都包装在一个go块中; go协调异步性是惊人的,但最终,渠道是一个渠道:

(defn my-post-request [channel options]
  (client/post http://www.example.com options
          (fn [{:keys [status headers body error]}] ;; asynchronous handle response
              (put! channel body))))

(defn request-caller [options]
  (let [channel (chan)]
    (my-post-request channel options)
    (json/parse-string (<!! channel))))
Run Code Online (Sandbox Code Playgroud)