简体   繁体   English

如何等待coffeescript(或javascript)中的回调?

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

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). 我正在开发一个密码管理器Web应用程序,该应用程序使用Parvez Anandam的pbkdf2.js进行密钥生成(即将文本密码转换为适用于AES的256位密钥)。 I'm using the project to learn coffeescript. 我正在使用该项目来学习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". 由于deriveKey立即返回,因此我没有数据,最后一行显示“ 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. 在Java中,我希望可以找回类似Future的对象,可以加入或等待它,但是我意识到我的后端习惯可能不适用于UI代码。 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. 因此,当您调用keygen时,您将提供finished函数,而finished将在key可用时finished任何需要做的事情。 Your finished would usually be an anonymous closure. finished通常是匿名关闭。

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. 如果您查看任何AJAX库(例如jQuery),都会看到很多这样的事情:将函数传递给函数,然后一直传递函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM