简体   繁体   English

可以将此ClojureScript转换为JavaScript吗?

[英]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. 我的朋友给我看了一篇博客文章,该文章利用了ClojureScript宏,他声称所提供的代码无法优雅地转换为JavaScript,因为JavaScript缺乏对语言的宏支持。 Specifically, the go macro in this code snippet is not possible in JavaScript 具体来说,此代码段中的go宏无法在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/ 资料来源: 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. 我不是在寻找一种解决方案,该解决方案以不同的方式执行相同的行为(例如setTimeout的三个无限循环,等等),但是具有与原始方法相同的“精神”的解决方案。

From the same blog, only six weeks later : 在同一博客上,仅六个星期后

Last night I expressed some frustration about the state and future of concurrency in JavaScript. 昨晚,我对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. 最后,我与David Herman进行了一些来回交流,他指出ES6 Generators可以表达Go和core.async的CSP风格。 […] [...]

What follows is a minimal amount of code that works in Node.js 0.11 with the ES6 harmony command line setting. 接下来是使用ES6和谐命令行设置在Node.js 0.11中工作的最少代码。 […] The insight is to combine Generators with Channels. […]洞察力是将Generators与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. 因此,是的,您需要可以yield ES6生成器和一个CSP库(不是JS内置的),但是您将拥有与原始版本完全相同的精神

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. 如果ES7获得async / await语法,则还可以使用基于Promise的通道实现,并且可以使用立即调用的async同步函数表达式(IIAFE)代替go调用。 Also have a look over here . 也可以在这里看看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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