简体   繁体   English

无法在 clojurescript 中使用异步函数

[英]Can't use async functions in clojurescript

I am trying to use a npm package in cljs called "systeminformation"我正在尝试在名为“systeminformation”的 cljs 中使用 npm package
most of its function are async and some are non-async它的大部分 function 是异步的,有些是非异步的
but I am unable to use async function, everything else work fine但我无法使用异步 function,其他一切正常
RELATED IMPORTS相关进口

[clojure.core.async :as async] 
["systeminformation" :as systeminformation]

Code I am trying to run我试图运行的代码

(comment
  (systeminformation/version) // WORKS FINE 
  (async/go
    (async/<! (systeminformation/cpu))) // Gives me error 
  )

ERROR:错误:

INFO [mutesync.inspect.electron.background.main:30] - STACK
 TypeError: c.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 is not a function
    at cljs$core$async$impl$ioc_helpers$take_BANG_ (D:\Tom\mutesync\.shadow-cljs\builds\electron-main\dev\out\cljs-runtime\cljs\core\async\impl\ioc_helpers.cljs:52:1)
    at switch__47338__auto__ (<eval>:8:52)
    at <eval>:32:29
    at Function.fexpr__47378 [as cljs$core$IFn$_invoke$arity$1] (<eval>:54:4)
    at Object.cljs$core$async$impl$ioc_helpers$run_state_machine [as run_state_machine] (D:\Tom\mutesync\.shadow-cljs\builds\electron-main\dev\out\cljs-runtime\cljs\core\async\impl\ioc
_helpers.cljs:43:3)
    at cljs$core$async$impl$ioc_helpers$run_state_machine_wrapped (D:\Tom\mutesync\.shadow-cljs\builds\electron-main\dev\out\cljs-runtime\cljs\core\async\impl\ioc_helpers.cljs:45:1)
    at <eval>:84:67
    at Immediate.cljs$core$async$impl$dispatch$process_messages (D:\Tom\mutesync\.shadow-cljs\builds\electron-main\dev\out\cljs-runtime\cljs\core\async\impl\dispatch.cljs:26:7)
    at processImmediate (internal/timers.js:456:21)
ERROR [mutesync.inspect.electron.background.main:68] - uncaught error
TypeError: c.cljs$core$async$impl$protocols$ReadPort$take_BANG_$arity$2 is not a function

Async functions in JS are syntax sugar for functions returning a Promise . JS 中的异步函数是返回Promise的函数的语法糖。

core.async does not work with Promises by default and you need to use the helper function to make them act like channels if you want to. core.async默认情况下不适用于 Promises,如果需要,您需要使用帮助程序 function 使它们像通道一样。 The <p! <p! macro does this for you.宏为您执行此操作。

(ns test.foo
  (:require
    [clojure.core.async :as async] 
    [cljs.core.async.interop :refer (<p!)]
    ["systeminformation" :as systeminformation]))


(async/go
  (prn (<p! (systeminformation/cpu))))

Alternatively you can just .then or .catch the Promise with a callback.或者,您可以使用回调.then.catch Promise。 There is no need for core.async when doing so.这样做时不需要core.async

(-> (systeminformation/cpu)
    (.then prn))

There is also a guide available on the topic.还有一个关于该主题的指南

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

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