【发布时间】: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()(不在它的回调中),是否会始终设置令牌?
【问题讨论】: