2

I'm having trouble with returning a value from a callback. I'm using https://github.com/transducer/cljs-iota which is a wrapper arounf the IOTA javascript library.

My code is :

(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)
          )

And the callback function is:

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

If I do

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

The callback prints to the console :

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

which is the result I want, but I get "result is" undefined.

I've been blocked on this for the whole day and I don't know why I can't return the result (if I try to return for example "hello" it doesn't work either), and my function works because I get the result back but cant return it...

If anyone has a suggestion...

1 Answer 1

2

I already answered on reddit but I'll add an answer here for posterity.

In callback style programming, you don't get a return. The callback needs to cause an effect somewhere, for example, by mutating an atom, putting something into a core.async channel, or resolving a promise (perhaps with the assistance of the promesa library. I prefer promises, but 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
                    )))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.