1

我无法从回调中返回值。我正在使用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.

我已经被阻止了一整天,我不知道为什么我不能返回结果(如果我尝试返回例如“你好”它也不起作用),我的函数工作是因为我得到结果,但不能返回它......

如果有人有建议...

4

1 回答 1

1

我已经在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
                    )))
于 2018-06-26T00:18:27.100 回答