开发者

How do I wait for a callback in coffeescript (or javascript)?

开发者 https://www.devze.com 2023-04-08 08:52 出处:网络
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 lea

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, siz开发者_StackOverflow中文版e_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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号