处理节点中的回调

时间:2012-09-26 00:08:34

标签: node.js callback

我还在学习节点编程....我正在使用express构建一个Web应用程序,并希望围绕基于事件的非阻塞I / O来解决其他回调中的其他函数的嵌套回调问题

以下是关于在任何地方使用回调的一个问题:

在大多数情况下我不能这样做(crypo会允许这种方法同步工作,所以这个例子没问题):

user.reset_password_token = require('crypto').randomBytes(32).toString('hex');

在我看到上面的例子有效之前,我不得不这样做:

User.findOne({ email: req.body.username }, function(err, user) {

  crypto.randomBytes(256, function(ex, buf) {
    if (ex) throw ex;
    user.reset_password_token = buf.toString('hex');
  });

  user.save(); // can I do this here?

  //will user.reset_password_token be set here??
  // Or do I need to put all this code into the randomBytes callback...
  //Can I continue programming the .findOne() callback here
    // with the expectation that
  //user.reset_password_token is set?
  //Or am I out of bounds...for the crypto callback to have been called reliably.
});

如果我在randomBytes代码之后调用user.save()(不在它的回调中),那么总是会设置令牌吗?

1 个答案:

答案 0 :(得分:1)

//will user.reset_password_token be set here?

没有。在您拥有的示例中,对crypto的调用是异步完成的,这意味着执行不会停止让调用结束,而是继续在findOne方法中执行代码。

User.findOne({ email: req.body.username }, function(err, user) {

  crypto.randomBytes(256, function(ex, buf) {
    if (ex) throw ex;
    user.reset_password_token = buf.toString('hex');

    // only within this scope will user.reset_password_token be
    // set as expected
    user.save();
  });

  // undefined since this code is called before the crypto call completes
  // (at least when you call crypto async like you have)
  console.log(user.reset_password_token);
});
相关问题