clojurescript - 如何从 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 等待并获取值。
我想回报一个承诺。
解决方案
这个函数接受一个通道并返回一个 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”。
推荐阅读
- google-cloud-platform - GKE 节点池升级最初因配额而停滞;无法回滚、取消或重试
- c - 如何找到源代码的依赖关系?
- swift - SwiftUI 工作表上的圆角
- django - 在 apache 和 daphne 上托管 django 频道
- java - Swing–JavaFX 互操作性 ConcurrentModificationException 错误
- python - 如何将 pyarrow 时间戳 dtype 转换为 time64 类型?
- discord - 在 discord.py 中获取成员的角色
- react-native - 如何在 React-Native 中创建一个分成 4 个部分的圆圈?
- python - 在 python 中的 bytes() 调用中用方括号括起整数是什么意思?
- c++ - 从用户输入的行和列中打印的更好方法?没有for循环?递归?