chovy
chovy

Reputation: 75864

handling callbacks in node

I'm still learning node programming....I'm building a web app using express and want to wrap my head around event-based non-blocking I/O with respect to nesting callbacks from other functions inside other callbacks.

Here is one issue that I am trying to understand with respect to using callbacks everywhere:

I cannot just do this in most cases (crypo will allow this method to work sync so this example is ok):

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

I was having to go about doing this before I saw that the above example works:

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.
});

If I call user.save() after the randomBytes code (not inside it's callback) will the token always be set?

Upvotes: 0

Views: 279

Answers (1)

Bill
Bill

Reputation: 25565

//will user.reset_password_token be set here?

No. In the example you have, the call to crypto is done asynchronously which means that execution will not stop to let that call finish and will instead continue executing code within your findOne method.

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);
});

Upvotes: 1

Related Questions