我如何等待中的CoffeeScript(或JavaScript)的回调? [英] How do I wait for a callback in coffeescript (or javascript)?

查看:131
本文介绍了我如何等待中的CoffeeScript(或JavaScript)的回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用帕尔韦兹Anandam的pbkdf2.js密钥生成一个密码管理Web应用程序(也就是,把文本密码成AES合适的256位密钥)。我使用该项目学习的CoffeeScript。我无法获取数据了回调。这里是我的code:

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

由于deriveKey立即返回,我没有数据 - 的最后一行打印出1。什么是处理这个正确的方法是什么?在java中我希望得到一个未来状物体后面,这点我可以加入或等待,但我知道,我的后端习惯可能不适合UI code。我应该从移动到加密和提交表单回调所说的'继续'功能?

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.

您会看到很多这样的事情,如果你看任何的AJAX库(如jQuery的):你传递函数的函数,函数一路下跌

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.

这篇关于我如何等待中的CoffeeScript(或JavaScript)的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆