如何在 CoffeeScript(或 JavaScript)中等待回调?

发布于 2024-12-07 03:51:13 字数 558 浏览 1 评论 0原文

我正在开发一个密码管理器 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谜兔 2024-12-14 03:51:13

通常的方法是发送异步任务完成时可以调用的回调函数。像这样的事情:

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

因此,当您调用 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文