0

我有一个小功能来验证用户输入。在该功能中,我还将检查电子邮件地址是否已被占用。但是我对异步回调有些麻烦。我希望任何人都可以给我一个提示,我该如何解决这个问题。我将 nodejs 与 express 3 框架、mongodb 和 node-validator 库一起使用。

这是我的验证功能的一部分:

function check(data, callback) {
    mongoose.model('User', User).count(data, function (err, count) {
        callback(err, !! count);
    });
};

function validate(email, password, confirm) {
    var v = new Validator(),
        errors = new Array();

    v.error = function (msg) {
        errors.push(msg);
    };

    check({email: email}, function (err, exists) {
        v.check(exists, { email: 'E-Mail is already taken' }).equals(false);
    });
    ...
    return errors;
}

基于异步回调,变量errorsreturn语句中为空。我怎么能检查电子邮件地址是否已经在数据库中?

4

2 回答 2

4

您将不得不为您的validate函数添加一个回调。就目前而言,您的check函数是异步的,因此您会立即返回空errors数组。

function check(data, callback) {
    mongoose.model('User', User).count(data, function (err, count) {
        callback(err, !! count);
    });
};

function validate(email, password, confirm, callback) {
    var v = new Validator(),
        errors = new Array();

    v.error = function (msg) {
        errors.push(msg);
    };

    check({email: email}, function (err, exists) {
        if (err) {
            return callback(err);
        }

        v.check(exists, { email: 'E-Mail is already taken' }).equals(false);
        callback(null, v);
    });
};

// Calling to validate example
server.get("/validate_user_or_whatever", function(req, resp) {
    // Call validate with callback
    validate(req.param("email"), req.param("password"), true, function(err, validator) {
        if (err) {
            return resp.json({success: false, message: err.message});
        }

        var success = validator.isValid; // or something

        // Respond with the results
        resp.json({success: success});
    });
});

现在,您的下一个问题可能是我如何运行所有这些 validate 函数并在调用 validate 之前等待它们返回callback。好问题,看看异步模块

于 2013-02-01T17:55:02.493 回答
2

您需要考虑异步并传递将异步调用的回调。快速示例:

app.get('/blah', function(req, res) {
   // Whatever
   validate(email, pass, confirm, function(errors) {
     if (errors.length == 0)
         resp.send(200, 'blah');
     else
         resp.send(400, 'blah blah');
   });
})

function validate(email, password, confirm, callback) {
    var v = new Validator(),
        errors = new Array();

    v.error = function (msg) {
        errors.push(msg);
    };

    check({email: email}, function (err, exists) {
        v.check(exists, { email: 'E-Mail is already taken' }).equals(false);
    }, function() {
        callback(errors);
    });
    // ...
    return errors;
}
于 2013-02-01T17:49:38.287 回答