关于 node.js 回调我不明白的地方

Something I don't understand about node.js callbacks

所以,我正在尝试向用户发送电子邮件确认令牌,为此,我正在尝试使用 crypto 模块来生成令牌。我有这个:

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

嗯,加密模块生成的令牌没有分配给 token variable,我认为这是因为 randomBytes 函数的异步性质。

我怎样才能真正...将令牌保存在某处以便我可以通过电子邮件发送它?或者 我是否必须在 randomBytes 回调函数中包含所有电子邮件发送代码? 这是必须在节点中完成的方式吗?有没有其他办法,让token及时生成,并真正发送出去?

抱歉,我是 node 的新手,有时我仍然对回调感到困惑。谢谢。

您真的应该将代码包装在函数中。它使管理回调和同时维护代码变得更加容易。看看我是如何修改您提供的内容的...请记住,我没有检查代码,因此可能存在一些错误。

var crypto = require('crypto'),
    transport = this.NewTransport(); // This generates a nodemailer transport

generateToken(sendMail);

function generateToken(callback) {
    // Generates the token
    var token;

    crypto.randomBytes(48, function(ex, buf) {
        token =  buf.toString('hex');

        if (typeof callback === 'function') {
            callback(token);
        }
    });
}

function sendMail(token) {
    // 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});
    });
}