I have a function that reads a file using js/FileReader.
:
(defn read-file [file]
(let [js-file-reader (js/FileReader.)]
(set! (.-onload js-file-reader)
(fn [evt]
(let [result (-> evt .-target .-result)
array (js/Uint8Array. result)]
{:content array}))) ; <- This is the value that 'read-file' should return
(.readAsArrayBuffer js-file-reader file)))
The problem is that I would like it to return the value of the .-onload
method of the FileReader
, but I only get (of course) the value of (.readAsArrayBuffer js-file-reader file)
which, naturally, is undefined
.
Thank you very much!
Edit
After trying with Martin Půda's answer, I think that the problem has to do with an asyncrhonous thing. I tested this code:
(defn read-file [file]
(let [js-file-reader (js/FileReader.)
reading-result (atom)
done? (atom false)]
(set! (.-onload js-file-reader)
(fn [evt]
(let [result (-> evt .-target .-result)
array (js/Uint8Array. result)]
(reset! reading-result {:content array})
(reset! done? true)
(js/console.log "in: " (:content @reading-result)))))
(.readAsArrayBuffer js-file-reader file)
;; (while (not @done?) (js/console.log (.-readyState js-file-reader)))
(js/console.log "out: " @reading-result)
@reading-result))
I get first the log of out: undefined
, and then the log of in:
(with the desired result).
When I uncomment the line (while...)
, I get an infinite loop of 1
's... So I think that the function never notices that the FileReader
was done... I don't know how to solve this...