I'm working on a password manager webapp that uses Parvez Anandam's pbkdf2.js for key generation (that is, turning a text password into a suitable 256 bit key for AES). I'm using the project to learn coffeescript. I'm having trouble getting the data out of the callbacks. Here's my code:
keygen = (password, salt, iterations) ->
key = 1
pbkdf = new PBKDF2 password, salt, iterations, size_in_bytes
pbkdf.deriveKey ((p) ->), ((k) ->
key = k
console.log "within callback " + key
)
console.log "straight line path " + key
Since deriveKey returns immediately, I don't have the data -- the last line prints "1". What's the proper way to deal with this? In java I would expect to get a Future-like object back, which I can join or wait on, but I realize that my backend habits may not be appropriate for UI code. Should I call a 'continue' function from the callback that moves on to the encryption and submitting the form?
The usual approach is to send in a callback function that the asynchronous task can call when it has finished. Something like this:
So you'd supply the
finished
function when you callkeygen
andfinished
would do whatever needs to be done when thekey
is available. Yourfinished
would usually be an anonymous closure.You'll see a lot of this sort of thing if you look at any of the AJAX libraries (such as jQuery): you pass functions to functions, functions all the way down.