如何 return 来自 go 块的承诺?

How to return a promise from a go block?

问题是如何将 go 块的结果发送到 nodejs 应用程序

无极解决?

Clojurescript 应用程序

(defn foo []  
  (go 1))

;;how to change foo,wrap to promise?, so node app can await to get  the 1
;;i used 1 for simplicity in my code i have something like
;;(go (let [x (<! ...)] x))

节点应用

async function nodefoo() {
  var x = await foo();
  console.log(x);     // i want to see 1
}

回调解决方案(现在有效的那个)
到目前为止,我只找到了一种传递 cb 函数的方法,所以这个 1 返回到 node.js app

Clojurescript 应用程序

(defn foo1 [cb]
  (take! (go 1)
         (fn [r] (cb r))))

节点应用

var cb=function () {....};
foo1(cb);   //this way node defined cb function will be called with argument 1

但我不想传递回调函数,我希望node.js等待并获取值。
我要return一个承诺。

此函数接受一个通道和 returns 一个 Javascript 以通道发出的第一个值解析的 Promise:

(defn wrap-as-promise
  [chanl]
  (new js/Promise (fn [resolve _] 
                    (go (resolve (<! chanl))))))

然后显示用法:

(def chanl (chan 1))
(def p (wrap-as-promise chanl))
(go
  (>! chanl "hello")
  (.then p (fn [val] (println val))))

如果你编译它并在你的浏览器中运行它(假设你调用了enable-console-print!)你会看到“你好”。