如何在 CoffeeScript(或 JavaScript)中等待回调?
我正在开发一个密码管理器 Web 应用程序,它使用 Parvez Anandam 的 pbkdf2.js 进行密钥生成(即将文本密码转换为适合 AES 的 256 位密钥)。我正在使用该项目来学习咖啡脚本。我无法从回调中获取数据。这是我的代码:
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
由于deriveKey立即返回,所以我没有数据——最后一行打印“1”。处理这个问题的正确方法是什么?在java中,我希望得到一个类似Future的对象,我可以加入或等待它,但我意识到我的后端习惯可能不适合UI代码。我应该从回调中调用“继续”函数来继续加密并提交表单吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常的方法是发送异步任务完成时可以调用的回调函数。像这样的事情:
因此,当您调用
keygen
时,您需要提供finished
函数,并且finished
会在>密钥
可用。你的finished
通常是一个匿名闭包。如果您查看任何 AJAX 库(例如 jQuery),您会看到很多这样的事情:您将函数传递给函数,一直向下传递函数。
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.