简体   繁体   English

javascript / express.js在自定义验证回调函数中未返回路由函数

[英]javascript / express.js not returning routing function in custom validation callback function

I expect the function app.patch to immediately return if the validation callback argument isValid is set to false in the validate function. 如果验证函数中的验证回调参数isValid设置为false,我希望函数app.patch立即返回。

but it is not :-/ 但是不是:-/

I can't see the error, what am I doing wrong? 我看不到错误,我在做什么错?

function route(app) {

    app.patch('/category/:category_id', function(req, res) {

        var id = req.params.category_id;
        var title = req.body.title;
        validate('title', title, function(response, isValid) {
            if(!isValid) {
                res.json(422, response);
                return;
            };
        }); 

        console.log("should not get to here"); 

        ...          
    });

    var validate = function validate(field, value, callback) {
        if (value === undefined || value.trim() === '') {
            var response = { };
            response.message = "Validation failed";
            callback(response, false);
        } else {
            callback(null, true);
        }
    };  
};

module.exports = route;

I can't see the error, what am I doing wrong? 我看不到错误,我在做什么错?

You return from the validate 's callback function, but not from the patch 's callback function. 您从validate的回调函数返回,但不是从patch的回调函数返回。

How can I improve my code? 如何改善我的代码?

If validate is synchronous (as in the code you posted), don't use a callback. 如果validate是同步的(如您发布的代码中所示),请不要使用回调。 Just return the result: 只需return结果:

app.patch('/category/:category_id', function(req, res) {
    var id = req.params.category_id;
    var title = req.body.title;
    var response = validate('title', title);
    if (response) {
        res.json(422, response);
        return;
    }
    console.log("will not get to here");
    …
});

function validate(field, value, callback) {
    if (value === undefined || value.trim() === '') {
        return response = {message: "Validation failed"};
    return null;
}

If you want/need to use callbacks, move all the code from should not get here into the validate callback function, after that if -statement where you return: 如果您希望/需要使用回调,请将所有代码从should not get here移到validate回调函数中,然后if -statement中返回:

app.patch('/category/:category_id', function(req, res) {
    var id = req.params.category_id;
    var title = req.body.title;
    validate('title', title, function(response, isValid) {
        if (!isValid) {
            res.json(422, response);
            return;
        }
        console.log("will not get to here"); 
        …
    });
});

function validate(field, value, callback) {
    // something async, then
        callback({message: "Validation failed"}, false);
    // or
        callback(null, true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM