So, I'm trying to send an email confirmation token to an user, and for that, I'm trying to use the crypto
module to generate the token. I have this:
var transport = this.NewTransport(), // This generates a nodemailer transport
token;
// Generates the token
require('crypto').randomBytes(48, function(ex, buf) {
token = buf.toString('hex');
});
// Uses nodemailer to send the message, with the token.
var message = {
from: 'test@email.com',
to: 'receiver@email.com',
subject: 'Token',
text: token,
html: token
};
transport.sendMail(message, function(err){
if(err) return res.send({s: 0});
return res.send({s: 1});
});
Well, the token generated by the crypto module isn't getting assigned to the token variable
, I assume this is because of the asynchronous nature of the randomBytes
function.
How can I actually... save the token somewhere so I can send it through the email? Or do I have to include ALL of the email-sending code inside of the randomBytes callback function? Is this the way it has to be done in node? Is there any other way, so that the token gets generated in time, and actually sent?
Sorry, I'm quite new to node and I'm still confused about callbacks sometimes. Thanks.