首页 > 解决方案 > 如何从 go 块返回一个承诺?

问题描述

问题是如何将 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 应用程序

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 等待并获取值。
我想回报一个承诺。

标签: clojurescript

解决方案


这个函数接受一个通道并返回一个 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!),您将看到“hello”。


推荐阅读