简体   繁体   中英

Is it possible to convert this ClojureScript to JavaScript?

My friend showed me a blog post that makes use of ClojureScript macros and he claims that the code provided cannot be elegantly converted to JavaScript because of JavaScript's lack of macro support in the language. Specifically, the go macro in this code snippet is not possible in JavaScript

(def c (chan))

(defn render [q]
  (apply str
    (for [p (reverse q)]
      (str "<div class='proc-" p "'>Process " p "</div>"))))

(go (while true (<! (timeout 250)) (>! c 1)))
(go (while true (<! (timeout 1000)) (>! c 2)))
(go (while true (<! (timeout 1500)) (>! c 3)))

(defn peekn
  "Returns vector of (up to) n items from the end of vector v"
  [v n]
  (if (> (count v) n)
    (subvec v (- (count v) n))
    v))

(let [el  (by-id "ex0")
      out (by-id "ex0-out")]
  (go (loop [q []]
        (set-html! out (render q))
        (recur (-> (conj q (<! c)) (peekn 10))))))

Source: http://swannodette.github.io/2013/07/12/communicating-sequential-processes/

I'm a bit hesitant to believe that it cannot be done without some sort of macro library in an elegant way. I am not looking for a solution that does the same behavior in a different way (such as three infinite loops of setTimeout, etc.), but one that has the same "spirit" as the original.

From the same blog, only six weeks later :

Last night I expressed some frustration about the state and future of concurrency in JavaScript. I ended up having a little bit of back and forth with David Herman and he pointed out that ES6 Generators can express Go and core.async's flavor of CSP. […]

What follows is a minimal amount of code that works in Node.js 0.11 with the ES6 harmony command line setting. […] The insight is to combine Generators with Channels.

So yes, you'll need ES6 generators that can yield , and a CSP library (not built into JS), but then you'll have exactly the same spirit as the original.

If ES7 gets async / await syntax, you can also use a promise-based channel implementation and would be able to use an immediately-invoked async chronous function expression (IIAFE) instead of the go call. Also have a look over here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM