从JavaScript回调返回值

时间:2018-06-25 14:18:25

标签: clojurescript clojurescript-javascript-interop

我在从回调返回值时遇到麻烦。我正在使用https://github.com/transducer/cljs-iota,它是IOTA javascript库的包装器。

我的代码是:

(defn find-transactions 
    "search transactions associated with an address and return a vector of hashes" 
    []
            (println "finding transactions")
            (iota-api/find-transactions eff.views/iota-instance {:addresses (list comment-address)} find-callback)
          )

回调函数是:

(defn find-callback [err hashes]
          (prn  "transactions found" hashes)
          hashes
    )

如果我这样做

(.log js/console "result is" (find-transactions))

回调将打印到控制台:

"transactions found" ["JW9QTNHDLGQYKGHLYHWHYRKTTEVUVBZSHNMLCDLBWVYPROKTCDRAMFGXMIQCEM9YIRXUSZJTEKG999999" "UTJ9YBLCE9RJIERRBX9HFANUYFALKZJHAPXWHQKS9KQJEKUQOTLDTSCKAM9KIFPNRXSEJCHTUJT999999" "PYWIZA9JAIPDEQBTMHSXVSKOLYGSNSMVQKOBT9WXHEFLFYCKEVPPRMGQXCBMACKSGJDQKTCUZXH999999" "XJPCFXWELTKSNCCZQM9QNTFMSRMNAEJ9WJWQERLMDSHQTGGQQHKZRZRANGRRXXTGSUNBSDFDBAC999999" "WVQIPEZZUPYODYFO9KYAIEQYPTGIMKDXGRPGF9ADDVKGGMRFKKASXQLKATFDIJJPWLOPSPPYURDSA9999" "QYKZWELJYAMWPITSTZSXLFFERSGRPBKIOCHSE9KLENRXNBXSGSLBEYW9JUVJYP9QWBJJFKMSUDA999999"]

这是我想要的结果,但是我得到了"result is" undefined

我整天都被阻止了,我不知道为什么我不能返回结果(如果我尝试返回例如“ hello”,它也不起作用),并且我的函数之所以有效,是因为我得到了结果,但无法返回...

如果有人有建议...

1 个答案:

答案 0 :(得分:1)

我已经回答了on reddit,但在此我将为后代添加一个答案。

在回调样式编程中,您不会得到回报。回调需要在某个地方产生效果,例如,通过使原子发生变异,将某些内容放入core.async通道或解析诺言(也许在promesa库的帮助下。我更喜欢诺言,但是ymmv。

(defn find-transactions
  "search transactions associated with an address and return a promise for vector of hashes" 
  []
  (println "finding transactions")
  (promesa/promise
    (fn [resolve _reject]
      (iota-api/find-transactions 
        eff.views/iota-instance 
        {:addresses (list comment-address)} 
        (fn [error hashes]
          (if (error)
            (reject error)
            (resolve hashes)))))))

(-> (find-transactions)
    (promesa/then (fn [result]
                    ; do something here with result
                    ))
    (promesa/then (fn [error]
                    ; do something with error
                    )))