【问题标题】:handling callbacks in node处理节点中的回调
【发布时间】:2012-09-26 08:17:39
【问题描述】:

我仍在学习节点编程....我正在使用 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()(不在它的回调中),是否会始终设置令牌?

【问题讨论】:

    标签: node.js callback


    【解决方案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);
    });
    

    【讨论】:

    • 您能描述一下处理这种情况的正确方法吗? (也就是说,在不允许同步行为作为 randomBytes 的函数的情况下)。
    猜你喜欢
    • 2017-02-24
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2014-06-09
    • 2013-04-06
    • 2023-04-07
    相关资源
    最近更新 更多