Question

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?

Was it helpful?

Solution

The usual approach is to send in a callback function that the asynchronous task can call when it has finished. Something like this:

keygen = (password, salt, iterations, finished) ->
  key = 1
  pbkdf = new PBKDF2 password, salt, iterations, size_in_bytes
  pbkdf.deriveKey ((p) ->), ((k) ->
    key = k
    console.log "within callback " + key
    finished key
    )
  console.log "straight line path " + key

So you'd supply the finished function when you call keygen and finished would do whatever needs to be done when the key is available. Your finished 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top