【问题标题】:javascript / express.js not returning routing function in custom validation callback functionjavascript / express.js 未在自定义验证回调函数中返回路由函数
【发布时间】:2014-07-20 15:09:21
【问题描述】:

如果验证函数中的验证回调参数 isValid 设置为 false,我希望函数 app.patch 立即返回。

但它不是:-/

我看不到错误,我做错了什么?

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;

【问题讨论】:

  • 你从validate的回调函数返回,而不是从patch的回调函数返回。
  • 如何改进我的代码?

标签: javascript express callback


【解决方案1】:

我看不到错误,我做错了什么?

您从validate 的回调函数返回,而不是从patch 的回调函数返回。

如何改进我的代码?

如果validate 是同步的(如您发布的代码中所示),请不要使用回调。就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;
}

如果您想要/需要使用回调,请将所有代码从 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);
}

【讨论】:

  • 知道了。感谢您的详细回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
相关资源
最近更新 更多